欢迎您访问 最编程 本站为您分享编程语言代码,编程技术文章!
您现在的位置是: 首页

vue wkwebview 下载文件

最编程 2024-07-17 14:47:45
...

首先:iOS 不支持 js 下载文件   
           vue 直接写 a标签 window.open 或者 是from表单 都不支持直接下载
但是:我们可一调用 safari 浏览器来实现,你可一通过js调用oc 方法在调用 safari 打卡你要下载文件的连接

wkwebview 实现WKScriptMessageHandler中userContentControllerdidReceiveScriptMessage方法 


 WKWebViewConfiguration * webConfiguration = [WKWebViewConfiguration new];

webConfiguration.preferences= [WKPreferencesnew];

webConfiguration.preferences.minimumFontSize=10;

webConfiguration.preferences.javaScriptEnabled=YES;

webConfiguration.preferences.javaScriptCanOpenWindowsAutomatically = YES;

//注入js方法

 [webConfiguration.userContentController addScriptMessageHandler:self name:@"file_url"]; 

webView = [[WKWebView alloc] initWithFrame:[UIScreen mainScreen].bounds configuration:webConfiguration];

webView.scrollView.alwaysBounceHorizontal = NO;//scrollView

webView.scrollView.alwaysBounceVertical=NO;//scrollView

NSString *urlStr = @"http://xxxxxxx";

NSURL*url = [NSURLURLWithString:urlStr];

NSURLRequest*request = [[NSURLRequestalloc]initWithURL:url];

webView.UIDelegate=self;

webView.navigationDelegate = self;

[webViewloadRequest:request];

[self.view addSubview:webView];

#pragma mark - WKScriptMessageHandler 实现方法

- (void)userContentController:(WKUserContentController*)userContentControllerdidReceiveScriptMessage:(WKScriptMessage*)message{

    NSLog(@"name:%@ \\\\n body:%@ \\\\n frameInfo:%@\\\\n",message.name,message.body,message.frameInfo);

    if([message.nameisEqualToString:@"file_url"]){

        NSString* string1 = [message.body stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];//中文转utf8 要不然不跳转哦。

        NSURL* url= [NSURLURLWithString:string1];

        [[UIApplication sharedApplication] openURL:url options:@{} completionHandler:^(BOOL success) {

        }];    }

}