使用AFNetworking在appdelegate中从网上下载pdf,然后尝试在另一个页面上的UIWebview中加载存储的pdf

时间:2013-05-22 13:29:28

标签: pdf uiwebview afnetworking

我正在使用AFNetworking下载pdf(每周更改一次)并使用以下代码将其保存到文档目录中:

//Get the PDF    

NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:@"http://www.somewebsiteaddress/CurrentEdition1.pdf"]];
AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request];

NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *filePath =  [documentsDirectory stringByAppendingPathComponent:@"CurrentEdition1.pdf"];

operation.outputStream = [NSOutputStream outputStreamToFileAtPath:filePath append:NO];

[operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
    NSLog(@"Successfully downloaded file to %@", filePath);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
    NSLog(@"Error: %@", error);
}];

[operation start];

然后我想在UIWebView中读取该应用程序的另一部分中的已保存文件(在下载之后)并使用此代码:

//Now create Request for the file that was saved in your documents folder

NSString *resourceDocPath = [[NSString alloc] initWithString:[[[[NSBundle mainBundle]  resourcePath] stringByDeletingLastPathComponent] stringByAppendingPathComponent:@"Documents"]];

NSString *filePath = [resourceDocPath stringByAppendingPathComponent:@"CurrentEdition1.pdf"];

NSURL *url = [NSURL fileURLWithPath:filePath];

NSURLRequest *requestObj = [NSURLRequest requestWithURL:url];

[webVieweedition setUserInteractionEnabled:YES];

[webVieweedition setDelegate:self];

[webVieweedition loadRequest:requestObj];

我使用了一些单页pdf文档进行测试 - 将它们加载到服务器上,然后查看它们是否已下载,然后在更改时查看。问题是,这似乎只占50%的时间。我将放置一个新文件,有时会在UIWebView中显示正确的文件,有时它会显示前一个而不是新文件。我等到我在尝试转到UIWebView之前看到下载完成消息(虽然我知道客户端不会这样做,但这是另一个问题)。无论如何,我是XCode的新手,并且刚刚成为一名网络html人。这让我的头旋转了两天。使用故事板,ARC,XCode 4.6.2。

1 个答案:

答案 0 :(得分:1)

如果我理解正确,有时你会在app中看到相同的pdf,虽然你在webserver上更改了它们?可能是缓存的原因,尝试以这种方式构造请求,忽略缓存

    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:@"http://www.somewebsiteaddress/CurrentEdition1.pdf"]  cachePolicy:NSURLRequestReloadIgnoringCacheData timeoutInterval:10];