背景
h5和native 互動代碼備援 不清晰 多人開發時效率地下
目的
為了尋找更搞笑的程式設計開發方式,節省代碼量,以及多人開發的效率
過程探索
JavaScriptCore
官方解釋
The JavaScriptCore Framework provides the ability to evaluate JavaScript programs from within Swift, Objective-C, and C-based apps. You can use also use JavaScriptCore to insert custom objects to the JavaScript environment.
JavaScriptCore架構提供了從Swift、Objective-C和基于c的應用程式中評估JavaScript程式的能力。您還可以使用JavaScriptCore将定制對象插入到JavaScript環境中。
蘋果爸爸在iOS7.0以後推出的官方庫,目前看起來是适用于UIWebView(官方以不推薦使用)
下面說一下使用方法
關鍵詞: JSContext JSValue JSExport
JSExport
繼承并申明你需要到protocol - 注入到JS裡到function
@objc protocol SwiftJavaScriptProtocol: JSExport {
func test(_ value: String?)
// js調用App的功能後 App再調用js函數執行回調
func callHandler(handleFuncName: String)
var stringCallback: (@convention(block) (String) -> String)? { get set }
}
申明一個繼承于NSObjectt的class, 并實作你的protocol
class SwiftJavaScriptModel: NSObject, SwiftJavaScriptProtocol {
weak var jsContext: JSContext? //js 的執行環境,調用js 或者注入js
var stringCallback: (@convention(block) (String) -> String)? // swift裡想要讓JS能夠調用我們的clourse,一定要用這個關鍵字
func test(_ value: String?) {
print("js call test(_ value: \(value ?? ""))")
}
func callHandler(handleFuncName: String) {
let jsHandlerFunc = self.jsContext?.objectForKeyedSubscript("\(handleFuncName)")
let dict = ["name": "sean", "age": 18] as [String : Any]
jsHandlerFunc?.call(withArguments: [dict])
}
override init() {
super.init()
self.stringCallback = {
[weak self] value in
print("SwiftJavaScriptModel stringCallback \(value)")
return value.appending("this is append string")
}
}
}
最後,通過UIWebView的特性,擷取JSContext,并将我們的function注入到上下文
extension JSCoreVC: UIWebViewDelegate {
func webViewDidFinishLoad(_ webView: UIWebView) {
if let jsContext = webView.value(forKeyPath:"documentView.webView.mainFrame.javaScriptContext") as? JSContext {
let model = SwiftJavaScriptModel()
model.jsContext = jsContext
jsContext.setObject(model, forKeyedSubscript: ("WebViewJavascriptBridge" as NSString)) //注入
jsContext.evaluateScript(self.htmlContent)
jsContext.exceptionHandler = {
[weak self] (context, exception) in
guard let self = self else { return }
print("exception:", exception)
}
}
}
}
WebViewJavascriptBridge 注意,這裡注入的名字即是JS調用的名字,JS調用我們的函數和自己的使用方式一樣,舉例如下
test
stringCallback
function appStringCallbackFunc(arg) {
let value = WebViewJavascriptBridge.stringCallback('this is toast')
document.getElementById('js-content').innerHTML = "App調用js回調函數啦, 傳回 ->" + value;
}
看起來很友善吧,app -> JS 也很友善
let context = JSContext()
let _ = context?.evaluateScript("var triple = (value) => value + 3") //注入
let returnV = context?.evaluateScript("triple(3)") // 調用
print("__testValueInContext --- returnValue = \(returnV?.toNumber())")
WKWebView
官方解釋
You can make POST requests with httpBody content in a WKWebView.
After creating a new WKWebView object using the init(frame:configuration:) method, you need to load the web content. Use the loadHTMLString(:baseURL:) method to begin loading local HTML files or the load(:) method to begin loading web content. Use the stopLoading() method to stop loading, and the isLoading property to find out if a web view is in the process of loading. Set the delegate property to an object conforming to the WKUIDelegate protocol to track the loading of web content. See Listing 1 for an example of creating a WKWebView programmatically.
你可以在WKWebView中用httpBody内容發出POST請求。
在使用init(frame:configuration:)方法建立一個新的WKWebView對象之後,您需要加載web内容。使用loadHTMLString(:baseURL:)方法開始加載本地HTML檔案,或使用load(:)方法開始加載web内容。使用stopLoading()方法停止加載,使用isLoading屬性查明web view是否在加載過程中。将委托屬性設定為符合WKUIDelegate協定的對象,以跟蹤web内容的加載。清單1給出了以程式設計方式建立WKWebView的示例。
WKWebView關鍵詞
WKUIDelegate WKNavigationDelegate WKScriptMessageHandler
//! WKWeView在每次加載請求前會調用此方法來确認是否進行請求跳轉
func webView(_ webView: WKWebView, decidePolicyFor navigationAction: WKNavigationAction, decisionHandler: @escaping (WKNavigationActionPolicy) -> Void) {
guard let url = navigationAction.request.url else {return}
guard let scheme = url.scheme else {return}
if scheme == "xdart" {
// THSchemeManager.handleScheme(url.absoluteString)
}
decisionHandler(.allow)
}
WKUIDelegate 基于JS系統的幾個内部方法 實作一下方法要調用對應的completionHandler,否則崩潰
func webView(_ webView: WKWebView, runJavaScriptAlertPanelWithMessage message: String, initiatedByFrame frame: WKFrameInfo, completionHandler: @escaping () -> Void) {
// call toast
completionHandler()
}
func webView(_ webView: WKWebView, runJavaScriptConfirmPanelWithMessage message: String, initiatedByFrame frame: WKFrameInfo, completionHandler: @escaping (Bool) -> Void) {
// call alert
completionHandler(true)
}
func webView(_ webView: WKWebView, runJavaScriptTextInputPanelWithPrompt prompt: String, defaultText: String?, initiatedByFrame frame: WKFrameInfo, completionHandler: @escaping (String?) -> Void) {
// call input
completionHandler("this is a message")
}
WKScriptMessageHandler 重點來了,這是蘋果爸爸推薦使用的JS互動
let content = WKUserContentController()
content.add(self, name: "artproFunc") //此方法會造成循環引用,注意時機釋放
let config = WKWebViewConfiguration()
config.userContentController = content
wkwebV = WKWebView.init(frame: self.view.bounds, configuration: config)
這裡往content裡注入的是JS調用APP的函數
JS通過window.webkit.messageHandlers.artproFunc.postMessage()給artproFunc發送消息
我們的解析在此方法裡
func userContentController(_ userContentController: WKUserContentController, didReceive message: WKScriptMessage) {
if message.name != self.applicationName { return }
if let body = message.body as? [String: Any],
let method = body["method"] as? String {
let aSel = NSSelectorFromString(method)
if !self.canPerformAction(aSel, withSender: nil) {
return
}
let para = body["parameter"]
let callback = body["callback"]
}
}
以我目前的項目為例,我們是将 artproFunc當作了一個通道,所有的function都走message.body分發出來,是以會有switch case 解析 body中的method,然後再進行不同的方法分發。
缺點
代碼備援
字元串分發,容易出錯
函數格式各式各樣,多人開發,他人不好接手

artpro_userContent.png
WebViewJavascriptBridge
最近研究JS和iOS native互動,偶然發現的庫發現github上用的人也不少,感覺還不錯的樣子,就研究了下使用方法

WebViewJavascriptBridge_star.png
看起來很簡單的樣子
bridge = WebViewJavascriptBridge.init(webV)
// js call app
bridge.registerHandler("testCallHandler") { [weak self](data, callback) in
guard let self = self else { return }
callback?("Response from testCallHandler")
}
// app call js
self.bridge.callHandler("testJavascriptHandler", data: ["foo": "before ready"])
WebViewJavascriptBridge 原理将在下篇文章中剖析
參考文檔1