iOS WKWebView 加载沙盒图片

2023-11-07  本文已影响0人  孔凡伍

1、 WebView解决跨域问题

// 解决跨域问题:h5 无法读取沙盒图片
[self.myWebView.configuration.preferences setValue:@YES forKey:@"allowFileAccessFromFileURLs"];

[self.myWebView.configuration.userContentController addScriptMessageHandler:weakSelf name:@"go_apppic"];

2、html 示例

<!DOCTYPE html>
<html>
<header>
    
<title id = "title">Title of this page</title>

<!--样式从File.css文件中获取-->
<link rel="stylesheet" type="text/css" href="File.css">
<!--样式改变适应手机屏幕大小-->
<meta name="viewport" content="width=device-width,initial-scale=1.0, minimum-scale=1.0, maximum-scale=1.0, user-scalable=no"/>
<!--响应的方法从File.js文件中获取-->
<!--<script type="text/javascript" src="File.js"></script>-->

</header>
<body>
    <button type="button" onclick = "JSCallOCMethod1()">JSCallOCMethod1</button>
    <br/><br/>
    <image id='img' width='200' height='300' src='https://picsum.photos/200/300'>
            
            
    <script type="text/javascript">
        
        function JSCallOCMethod1() {
            console.log('JSCallOCMethod1');
            window.webkit.messageHandlers.go_apppic.postMessage({"funkey":"funkey"});
        }
        
        function go_apppic_back(funk, jsonString){
            console.log(jsonString);
            let jsonStr = decodeURI(jsonString);
            let res = JSON.parse(jsonStr);
            console.log(res);
            let values = Object.values(res)
            console.log(values[0]);
            document.getElementById('img').src = values[0];
        }
    </script>
</body>
</html>

3、回调JS

NSString *jsStr = [NSString stringWithFormat:@"%@('%@', '%@')",@“ go_apppic_back”, @“”,@“”];
[self.myWebView evaluateJavaScript:jsStr completionHandler:^(id _Nullable res, NSError * _Nullable error) {
 }];
上一篇下一篇

猜你喜欢

热点阅读