/**
下载文档
*/
- (IBAction)xiazai:(id)sender {
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths lastObject];
NSFileManager *fileManager = [NSFileManager defaultManager];
NSString *filePath = [documentsDirectory stringByAppendingPathComponent:self.filename];
if ([fileManager fileExistsAtPath:filePath]) {
//文件已经存在,直接打开
UIAlertController * alertController = [UIAlertController alertControllerWithTitle:@"是否打开文件?" message:nil preferredStyle:UIAlertControllerStyleAlert];
UIAlertAction * cancelAction =[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil];
[alertController addAction:cancelAction];
[alertController addAction:[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDestructive handler:^(UIAlertAction * _Nonnull action) {
[self openDocxWithPath:filePath];
}]];
[self presentViewController:alertController animated:YES completion:nil];
}else {
//文件不存在,要下载
UIAlertController * alertController = [UIAlertController alertControllerWithTitle:@"是否下载并打开文件?" message:nil preferredStyle:UIAlertControllerStyleAlert];
UIAlertAction * cancelAction =[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil];
[alertController addAction:cancelAction];
[alertController addAction:[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDestructive handler:^(UIAlertAction * _Nonnull action) {
[self downloadDocxWithDocPath:documentsDirectory fileName:self.filename];
}]];
[self presentViewController:alertController animated:YES completion:nil];
}
}
-(void)downloadDocxWithDocPath:(NSString *)docPath fileName:(NSString *)fileName{
[SVProgressHUD show];
//创建 Request
NSURLRequest* request = [NSURLRequest requestWithURL:[NSURL URLWithString:self.url]];
AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
NSURLSessionDownloadTask *task = [manager downloadTaskWithRequest:request progress:^(NSProgress * _Nonnull downloadProgress) {
NSLog(@"下载进度:%f",downloadProgress.fractionCompleted);
} destination:^NSURL * _Nonnull(NSURL * _Nonnull targetPath, NSURLResponse * _Nonnull response) {
[SVProgressHUD dismiss];
NSString *path = [docPath stringByAppendingPathComponent:fileName];
return [NSURL fileURLWithPath:path];
} completionHandler:^(NSURLResponse * _Nonnull response, NSURL * _Nullable filePath, NSError * _Nullable error) {
[SVProgressHUD dismiss];
NSString *name = [filePath path];
[self openDocxWithPath:name];
}];
[task resume];//开始下载 要不然不会进行下载的
}
-(void)openDocxWithPath:(NSString *)filePath {
//我是用网页打开的
SafariVC *vc = [[SafariVC alloc] init];
vc.url = self.url;
[self push:vc];
}