2

我有一个下载文件并将其存储在文档文件夹中的代码:

NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:file.url]];
AFURLConnectionOperation *operation =   [[AFHTTPRequestOperation alloc] initWithRequest:request];

NSArray   *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString  *documentsDirectory = [paths objectAtIndex:0];
NSString  *filePath = [NSString stringWithFormat:@"%@/%@", documentsDirectory, file.name];
operation.outputStream = [NSOutputStream outputStreamToFileAtPath:filePath append:NO];
[operation start];

请求完成后,我想使用以下代码在 UIWebView 上显示相同的文件:

[operation setCompletionBlock:^{
  dispatch_sync(dispatch_get_main_queue(), ^{
   UIWebView* webView = [[UIWebView alloc] init];
   NSURL *targetURL = [[NSBundle mainBundle] URLForResource:file.nameWithoutExtension withExtension:@"pdf"];
   webView.delegate = self;
   NSURLRequest *request = [NSURLRequest requestWithURL:targetURL];
   [webView loadRequest:request];

   ViewerVC* viewer = [[ViewerVC alloc] init];
   [viewer.view addSubview:webView];

   [self.navigationController pushViewController:viewer animated:FALSE];
 });
});

但是它不起作用,URL没有找到我刚刚下载的文件,是我保存还是搜索错误?

(为了便于理解,代码与我的实际代码略有不同,但想法是一样的。我什至用一些硬编码的 URL 尝试了这个示例,例如:http ://www.selab.isti.cnr.it/ws-伴侣/example.pdf

4

1 回答 1

2

[[NSBundle mainBundle] URLForResource:file.nameWithoutExtension withExtension:@"pdf"]将为您提供xcode 项目文件夹中的文件。

用这个

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

它会从 Documents 文件夹中获取一个文件。

于 2013-10-11T16:02:36.387 回答