记录一次H5生成blob文件url,iOS app内部WKWebView不能正常下载问题。
因为我发现在系统浏览器Safari里能下载,按理说在WKWebView里也能,后来查了下资料解决了这个问题。
1.首先要拦截跳转把以blob开头的跳转链接转成WKNavigationActionPolicyDownload 代码如下,注意这个只能在iOS14.5以后才能使用
- (void)webView:(WKWebView *)webView decidePolicyForNavigationAction:(WKNavigationAction *)navigationAction decisionHandler:(void (^)(WKNavigationActionPolicy))decisionHandler{
if([navigationAction.request.URL.absoluteString hasPrefix:@"blob"]){
if (@available(iOS 14.5, *)) {
decisionHandler(WKNavigationActionPolicyDownload);
} else {
// Fallback on earlier versions
decisionHandler(WKNavigationActionPolicyCancel);
}
}
else{
decisionHandler(WKNavigationActionPolicyAllow);
}
}
2.然后实现代理方法
- (void)webView:(WKWebView *)webView navigationAction:(WKNavigationAction *)navigationAction didBecomeDownload:(WKDownload *)download API_AVAILABLE(ios(14.5)){
download.delegate = self;// 遵守WKDownloadDelegate
}
3.最后实现WKDownloadDelegate代理
- (void)download:(WKDownload *)download decideDestinationUsingResponse:(NSURLResponse *)response suggestedFilename:(NSString *)suggestedFilename completionHandler:(void (^)(NSURL * _Nullable))completionHandler API_AVAILABLE(ios(14.5)){
NSURL *temporaryDirectory = [NSFileManager.defaultManager temporaryDirectory];
NSURL *url = [temporaryDirectory URLByAppendingPathComponent:suggestedFilename];
completionHandler(url);
//这里是提示框
[ShowAlertTool showSheetwithTitles:@[@"分享文件"] confirmBlock:^(NSInteger number) {
SHOW_HUD;
XMainAfter(1, ^{
DISMISS_HUD;
});
//这里是分享文件 封的一个方法,内部用的UIActivityViewController ,下面顺便会把分享代码也贴出来
[SFShare showSystemShare:@[url] completion:nil];
}];
}
4.分享方法的代码
+(void)showSystemShare:(NSArray *)items completion:(ShareCallBackBlock)shareBlock{
UIActivityViewController *activityView = [[UIActivityViewController alloc] initWithActivityItems:items applicationActivities:nil];
activityView.excludedActivityTypes = @[UIActivityTypePostToFacebook,
UIActivityTypeMessage,
UIActivityTypePostToTwitter,
UIActivityTypePostToWeibo,
UIActivityTypeMail,
UIActivityTypePrint,
UIActivityTypeCopyToPasteboard,
UIActivityTypeAssignToContact,
// UIActivityTypeSaveToCameraRoll,
UIActivityTypeAddToReadingList,
UIActivityTypePostToFlickr,
UIActivityTypePostToVimeo,
UIActivityTypePostToTencentWeibo,
UIActivityTypeAirDrop,
UIActivityTypeOpenInIBooks,
UIActivityTypeMarkupAsPDF,
];
activityView.completionWithItemsHandler = ^(UIActivityType __nullable activityType, BOOL completed, NSArray * __nullable returnedItems, NSError * __nullable activityError){
if (activityType == UIActivityTypeSaveToCameraRoll) {//保存到相册
NSString *msg = nil ;
if(!completed){
msg = @"保存图片失败" ;
}else{
msg = @"保存图片成功" ;
}
[[UIApplication sharedApplication].keyWindow makeToast:(msg) duration:1.5 position:CSToastPositionCenter];
}
if(shareBlock){
shareBlock(completed);
}
};
[[UIApplication sharedApplication].keyWindow.rootViewController presentViewController:activityView animated:YES completion:nil];
}
总结:这个功能只能在iOS14.5以上才能使用,因为网上关于iOS处理的资料有点少,就特地分享出来。希望能帮到iOS开发小伙伴们。
网友评论