将下载的pdf文件存储在文档目录中并检索

时间:2014-04-16 07:03:25

标签: ios pdf

这里正在创建下载任务

- (void)viewDidLoad
{
    [super viewDidLoad];

    NSURLSessionConfiguration *sessionConfiguration = [NSURLSessionConfiguration defaultSessionConfiguration];
    NSURLSession *session = [NSURLSession sessionWithConfiguration:sessionConfiguration delegate:self delegateQueue:nil];
    NSURLSessionDownloadTask *downloadTask = [session downloadTaskWithURL:[NSURL URLWithString:@"http://app.msf.gov.sg/Portals/0/Summary/assistance/CSSD/ComCare%20@%20a%20Glance%20-%20English%20(final).pdf"]];
    [downloadTask resume];
    // Do any additional setup after loading the view from its nib.
}

这里正在成功下载pdf文件

- (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didFinishDownloadingToURL:(NSURL *)location {
    NSData *data = [NSData dataWithContentsOfURL:location];

    dispatch_async(dispatch_get_main_queue(), ^{
        [self.progressView setHidden:YES];

    });
}

现在我的问题是我如何存储该pdf文件并再次检索 请帮我 提前谢谢..

2 个答案:

答案 0 :(得分:0)

只需将文件从“位置”移动到您的文档目录:

NSFileManager *fileManager = [NSFileManager defaultManager];
NSURL *docFolder = [[fileManager URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask] firstObject];
NSURL *fileURL = [docFolder URLByAppendingPathComponent:@"file.pdf" isDirectory:NO];
[fileManager moveItemAtURL: location toURL:fileURL error:nil];

NSLog(@" pdf file is here %@", fileURL);

答案 1 :(得分:0)

  • 我们必须将位置复制到我们的文档目录

    NSError *error;
    
    NSString *fileName = downloadTask.originalRequest.URL.lastPathComponent;
    
    NSArray *docDir = NSSearchPathForDirectoriesInDomains(NSDocumentationDirectory, NSUserDomainMask, YES);
    NSString *loc = [docDir objectAtIndex:0];
    NSString *filePathName = [loc stringByAppendingString:fileName];
    
    NSFileManager *fileMgr = [NSFileManager defaultManager];
    
    if ([fileMgr fileExistsAtPath:filePathName]) {
        [fileMgr removeItemAtPath:filePathName error:&error];
    }
    
    BOOL success =  [fileMgr copyItemAtPath:[location path] toPath:filePathName error:&error];
    if (success) {
        NSLog(@"FIle is successfully copied to documents directory");
    }else{
        NSLog(@"error:%@",error.description);
    }