近期由于項(xiàng)目需求,在用UIWebView 加載網(wǎng)頁(yè)的時(shí)候晰房,發(fā)現(xiàn)網(wǎng)頁(yè)上面有莫名的異常,然后用WKWebView加載沒有上述問題射沟,想到可能是UIWebView 的問題殊者,而是果斷換了,現(xiàn)在分享一些經(jīng)驗(yàn)验夯。
㈠猖吴、后臺(tái)對(duì)于iOS端做的很簡(jiǎn)單,就是只需要一段代碼就可以如下:
window.webkit.messageHandlers.input.postMessage(null);
input:為注入JS的對(duì)象挥转,這個(gè)名稱可以前端定義海蔽,也可以iOS移動(dòng)端定義;
唯一需要前端多做點(diǎn)的就是需要做一下平臺(tái)判斷绑谣。
iOS平臺(tái)需要:
import WebKit
/// 配置網(wǎng)頁(yè)視圖:
let webConfiguration = WKWebViewConfiguration()
WKWebViewConfiguration党窜,可以配置網(wǎng)頁(yè)顯示的屬性,不過一般不做操作借宵,除非有特殊要求幌衣;
/**
* WKUserContentController 用于給JS注入對(duì)象,注入對(duì)象后壤玫,JS端就可以使用
*/
// 通過JS與webview內(nèi)容交互
let userContentController = WKUserContentController()
userContentController.add(self, name: "input")
//
webConfiguration.userContentController = userContentController
extension WebViewViewController: WKScriptMessageHandler {
func userContentController(_ userContentController: WKUserContentController, didReceive message: WKScriptMessage) {
VCUtils.dPrint("message.body:\(message.body)")
var bodyDict: Dictionary = [String: Any]()
if message.name == "input" {
self.input()
}
}
private func input() {
// "show('\(accountManager.account.getMobileNo())', '\(accountManager.account.userInfo.customerName)', '\(accountManager.account.userInfo.idNo)')"該字符串為iOS傳遞給JS的數(shù)據(jù) 豁护,show 為JS端接收方法名稱
self.webView.evaluateJavaScript("show('\(accountManager.account.getMobileNo())', '\(accountManager.account.userInfo.customerName)', '\(accountManager.account.userInfo.idNo)')") { (result, error) in
print("input result::\(String(describing: result))")
}
寫完瞬間感覺完爆UIWebView有木有,比它簡(jiǎn)單多了欲间。
此例已經(jīng)在我的項(xiàng)目代碼中親測(cè)有效楚里,并且已經(jīng)上線使用,所以大家可以放心使用猎贴,不過此處我只提供一些WKWebView與 JS交互的方式和前端需要做的事情班缎,并未闡述WKWebView 內(nèi)部API蝴光,需要了解的可以點(diǎn)擊下面的鏈接。最后初始化之后一定要實(shí)現(xiàn)其協(xié)議吝梅,否則協(xié)議下面的方法無法調(diào)用虱疏。