从url下载PDF文件并重用下载的文件

时间:2015-09-19 15:22:16

标签: ios objective-c

我正在开发一个应用程序,我有几个pdf网址可以从互联网上获取。当用户点击名为pdf文件的单元格时,此pdf应在UIWebView中打开并存储在手机上,以便下次用户点击该行时,文件从应用程序加载而不是从互联网。

我已经找了一周,我找不到任何解决方案,有人可以帮我吗?

由于

2 个答案:

答案 0 :(得分:2)

您可以这样做:

// Get the PDF Data from the url in a NSData Object
NSData *pdfData = [[NSData alloc] initWithContentsOfURL:[NSURL URLWithString:@"http://www.example.com/info.pdf"]];


// Store the Data locally as PDF File
NSString *resourceDocPath = [[NSString alloc] initWithString:[
    [[[NSBundle mainBundle] resourcePath] stringByDeletingLastPathComponent]
        stringByAppendingPathComponent:@"Documents"
]];

NSString *filePath = [resourceDocPath  stringByAppendingPathComponent:@"myPDF.pdf"];
[pdfData writeToFile:filePath atomically:YES];

// Now create Request for the file that was saved in your documents folder
NSURL *url = [NSURL fileURLWithPath:filePath];
NSURLRequest *requestObj = [NSURLRequest requestWithURL:url];

[webView setUserInteractionEnabled:YES];
[webView setDelegate:self];
[webView loadRequest:requestObj];

答案 1 :(得分:1)

我终于通过找到一些答案并将它们合并来解决它。

NSString *path = [NSString stringWithFormat:@"%@/%@",[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0],@"fileName.pdf"]; 
NSMutableArray *directory = [[fullPath componentsSeparatedByString:@"/"] mutableCopy]; 
[directory removeObjectAtIndex:[directory count]-1]; 
NSError *error = [[NSError alloc]init]; 
if (![[NSFileManager defaultManager] fileExistsAtPath:[directory componentsJoinedByString:@"/"]]){ 
[[NSFileManager defaultManager] createDirectoryAtPath:[directory componentsJoinedByString:@"/"] withIntermediateDirectories:YES attributes:nil error:&error]; 
} 
[data writeToFile:fullPath atomically:NO];