NSURL *url = [NSURL URLWithString:@"PDFLINK"];
// Get the PDF Data from the url in a NSData Object
NSData *pdfData = [[NSData alloc] initWithContentsOfURL:url];
NSString * name = @"First";
// Store the Data locally as PDF File
NSFileManager *fileManager = [NSFileManager defaultManager];
NSString *documentsDirectory = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) firstObject];
NSString *newFilePath = [documentsDirectory stringByAppendingPathComponent:@"my.pdf"];
NSError *error;
if ([fileManager createFileAtPath:newFilePath contents:pdfData attributes:nil])
{
NSLog(@"Create Sucess");
[self loadPDF];
}
else
{
NSLog(@"Create error: %@", error);
}
}
-(void)loadPDF
{
NSFileManager *fileManager = [NSFileManager defaultManager];
NSString *documentsDirectory = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) firstObject];
NSArray *resultArray = [fileManager subpathsOfDirectoryAtPath:documentsDirectory error:nil];
if (![resultArray containsObject:arrObj])
{
// do something
}
NSString *filePath = [documentsDirectory stringByAppendingPathComponent:[resultArray objectAtIndex:0]];
// Now create Request for the file that was saved in your documents folder
//NSLog(@"The filePath %@",filePath);
NSURL *url = [NSURL fileURLWithPath:filePath];
NSLog(@"The url %@",url);
NSURLRequest *requestObj = [NSURLRequest requestWithURL:url];
[_webView setUserInteractionEnabled:YES];
[_webView setDelegate:self];
[_webView loadRequest:requestObj];
}
这是我的代码。我有更多的10 pdf,并希望将它们本地存储在设备上并在下次显示而无需下载。
它再次保存pdf,我无法检查是否已下载?
请帮帮我
答案 0 :(得分:0)
我不确定你的意思但是,要下载文件,你需要使用NSData:
NSString *stringURL = @"your file URL";
NSURL *url = [NSURL URLWithString:stringURL];
NSData *urlData = [NSData dataWithContentsOfURL:url];
if ( urlData )
{
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *filePath = [NSString stringWithFormat:@"%@/%@", documentsDirectory,@"filename.extension"];
[urlData writeToFile:filePath atomically:YES];
}
现在下载的文件存在于filePath中,您可以使用以下命令获取它:
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *filePath = [documentsDirectory stringByAppendingPathComponent:@"filename with extension"];
NSString *content = [NSString stringWithContentsOfFile:filePath encoding:NSUTF8StringEncoding error:NULL];
您可以尝试检查文件路径中是否存在文件:
NSString* documentsPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
NSString* file = [documentsPath stringByAppendingPathComponent:@"filename"];
BOOL fileExists = [[NSFileManager defaultManager] fileExistsAtPath:file];
if(fileExists){
//dont download, just grab it and display it
}
else{
//download and display it
}