@interface WebViewController()<UIDocumentInteractionControllerDelegate>
@property (nonatomic, copy) NSString *fileName; //文件名
@property (nonatomic, strong) UIDocumentInteractionController *documentInteractionController;
@end
- (void)webView:(WKWebView *)webView decidePolicyForNavigationResponse:(WKNavigationResponse *)navigationResponse decisionHandler:(void (^)(WKNavigationResponsePolicy))decisionHandler {
self.fileName = navigationResponse.response.suggestedFilename; //获取文件名称
decisionHandler(WKNavigationResponsePolicyAllow);
}
//保存到文件(弹出菜单点击存储到“文件”,即可把文件保存到手机文件中)
-(void)saveToFile{
NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:configuration];
NSURL *URL = [NSURL URLWithString:self.currentURL];
NSURLRequest *request = [NSURLRequest requestWithURL:URL];
//判断是否存在
if([self isFileExist:self.fileName]) {
NSURL *documentsDirectoryURL = [[NSFileManager defaultManager] URLForDirectory:NSDocumentDirectory inDomain:NSUserDomainMask appropriateForURL:nil create:NO error:nil];
NSURL *url = [documentsDirectoryURL URLByAppendingPathComponent:self.fileName];
self.documentInteractionController = [UIDocumentInteractionController
interactionControllerWithURL:url];
[self.documentInteractionController setDelegate:self];
[self.documentInteractionController presentOpenInMenuFromRect:CGRectZero inView:self.view animated:YES];
[self.documentInteractionController presentPreviewAnimated:YES];
}else {
[MBProgressHUD showHUDAddedTo:self.view animated:YES];
weakify(self);
NSURLSessionDownloadTask *downloadTask = [manager downloadTaskWithRequest:request progress:^(NSProgress *downloadProgress){
} destination:^NSURL *(NSURL *targetPath, NSURLResponse *response) {
NSURL *documentsDirectoryURL = [[NSFileManager defaultManager] URLForDirectory:NSDocumentDirectory inDomain:NSUserDomainMask appropriateForURL:nil create:NO error:nil];
NSURL *url = [documentsDirectoryURL URLByAppendingPathComponent:weakSelf.fileName];
return url;
} completionHandler:^(NSURLResponse *response, NSURL *filePath, NSError *error) {
[MBProgressHUD hideHUDForView:weakSelf.view animated:YES];
weakSelf.documentInteractionController = [UIDocumentInteractionController
interactionControllerWithURL:filePath];
[weakSelf.documentInteractionController setDelegate:weakSelf];
[weakSelf.documentInteractionController presentOpenInMenuFromRect:CGRectZero inView:weakSelf.view animated:YES];
[weakSelf.documentInteractionController presentPreviewAnimated:YES];
}];
[downloadTask resume];
}
}
网友评论