iOS 檔案下載和開啟,iOS檔案下載開啟
最近的項目要用到一個線上報告的下載,於是完成後自己在理一下思路,大體的實現了我要得需求。
話不多說,直接上代碼
首先,取到網路檔案的連結,進行判段是否需求再次下載還是直接開啟
#pragma mark 下載報告
//// 第一步
//是否下載還是開啟檔案
- (void)downloadPDF:(NSString *)downloadUrl{
NSArray *array = [downloadUrl componentsSeparatedByString:@"/"]; //從字元/中分隔成多個元素的數組
NSString *file = [array lastObject];
if ([self isFileExist:file]) {
//擷取Documents 下的檔案路徑
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *path = [paths objectAtIndex:0];
NSString *pathString = [path stringByAppendingFormat:@"/%@",file];
NSLog(@"path:%@", pathString);
[self loadDocument:pathString];
}else{
//從新下載
[self downloadFile:downloadUrl];
}
}
#pragma mark 第二步 判斷沙箱中是否存在此檔案
-(BOOL) isFileExist:(NSString *)fileName
{
//擷取Documents 下的檔案路徑
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *path = [paths objectAtIndex:0];
NSString *filePath = [path stringByAppendingPathComponent:fileName];
NSFileManager *fileManager = [NSFileManager defaultManager];
BOOL result = [fileManager fileExistsAtPath:filePath];
NSLog(@"這個檔案已經存在:%@",result?@"是的":@"不存在");
return result;
}
////////// 第三步
//下載PDF
- (void)downloadFile:(NSString *)downLoadUrl{
__weak typeof(self)weakSelf = self;
[self hudTipWillShow:YES];
[DataService downloadTaskWithURL:downLoadUrl completion:^(id result) {
NSLog(@"%@",result);
NSProgress *downloadProgress = result;
if (weakSelf.HUD) {
weakSelf.HUD.progress = downloadProgress.fractionCompleted;
_HUD.labelText = [NSString stringWithFormat:@"%2.f%%",downloadProgress.fractionCompleted*100];
}
} filesPath:^(id filesPath) {
[_rePortDwn setBackgroundImage:[UIImage imageNamed:@"downLoad"] forState:UIControlStateNormal];
// NSLog(@"%@",filesPath);
NSURL*urlString = filesPath;
NSString *string = [urlString absoluteString];
NSArray *array = [string componentsSeparatedByString:@"/"]; //從字元A中分隔成2個元素的數組
NSString *file = [array lastObject];
NSLog(@"filePathName = :%@",file);
[weakSelf hudTipWillShow:NO];
}];
}
/////// 第四步
//已經下載了的檔案用webview顯示
-(void)loadDocument:(NSString *)documentName
{
UIWebView *webView = [[UIWebView alloc]initWithFrame:CGRectMake(0, 64, kSCREEN_WIDTH, kSCREEN_HEIGHT)];
[self.view addSubview:webView];
NSURL *url = [NSURL fileURLWithPath:documentName];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
[webView loadRequest:request];
}
最後,直接調用第一步的方法就可以了。
這其中沒有做斷點續傳,日後有遇到再更新!