WKWebView 初始化设置
let Configuration = WKWebViewConfiguration()
let controller = WKUserContentController()
let Preferences = WKPreferences()
Configuration.preferences = Preferences
controller.add(self, name: "doActionMsg") // 注入js方法
Configuration.preferences.javaScriptEnabled = true
Configuration.preferences.javaScriptCanOpenWindowsAutomatically = true
Configuration.allowsInlineMediaPlayback = true
if #available(iOS 9.0, *) {
Configuration.requiresUserActionForMediaPlayback = false
} else {
// Fallback on earlier versions
}
Configuration.userContentController = controller
let processPool = WKProcessPool()
Configuration.processPool = processPool
webView = WKWebView(frame: CGRect(x: 0, y: 0, width: Wi, height: Hi-navigationTopHeight), configuration: Configuration)
webView.backgroundColor = UIColor.white
let request = URLRequest(url: URL(string: self.urlString)!)
// webView.navigationDelegate = self
// webView.uiDelegate = self
webView.load(request as URLRequest)
webView.scrollView.showsVerticalScrollIndicator = true
webView.scrollView.delegate = self
self.view.addSubview(webView)
WKWebView代理方法
func userContentController(_ userContentController: WKUserContentController, didReceive message: WKScriptMessage) {
if message.name == "doActionMsg" { // 约定好的方法
if let bodyStr:String = message.body as? String { // 返回参数
let dict:Dictionary = getDictionaryFromJSONString(jsonString: bodyStr)
print("dict____",dict)
}
}
}
网友评论