源碼在這,看不懂的直接擼源碼就行,轉載聲明出處java
這是代碼流程git
// JS數據 func getJSVar() { let context: JSContext = JSContext() //定義JS環境 let result1: JSValue = context.evaluateScript("1 + 1") //執行JS代碼 print(result1) // 輸出2 // 定義js變量和函數 context.evaluateScript("function sum(param1, param2) { return param1 + param2; }") //經過下標來獲取js方法並調用方法 let pp_func = context.objectForKeyedSubscript("sum") let result = pp_func?.call(withArguments: [10,10]).toString() print(result!) //輸出20 //下標獲取js數組的值 context.evaluateScript("var names = ['vincen1', 'vincen2', 'vincen3']") let names = context.objectForKeyedSubscript("names") let name = names?.objectAtIndexedSubscript(0).toString() print(name ?? "空值處理") //輸出 Grace }
import UIKit import JavaScriptCore @objc protocol swiftDelegate : JSExport { func wxPay(_ orderNo: String) //這裏的方法與JS調用名相同 func wxShare(_ dict: [String : AnyObject]) func showDMessage(_ dict1:[String : String], _ dict2 : String) // js調用App的功能後 App再調用js函數執行回調 func callHandler(_ handleFuncName: String) } @objc class javaScriptModel: NSObject ,swiftDelegate { weak var controller: UIViewController? weak var jsContext: JSContext? func wxPay(_ orderNo: String) { // print("訂單號:", orderNo) showDialog("", message: "獲取到訂單號\(orderNo),調用微信支付") // 調起微信支付邏輯 } func showDMessage(_ dict1: [String : String], _ dict2: String) { showDialog("", message:"我是第一個字典\(dict1)-----我是第二個字符串\(dict2)") } func wxShare(_ dict: [String : AnyObject]) { showDialog("", message: "獲取到分享的字典\(dict),調用微信支付") } func callHandler(_ handleFuncName: String) { let jshandFunc = jsContext?.objectForKeyedSubscript("\(handleFuncName)") let dict = ["name" : "pp"] as [String : Any] jshandFunc?.call(withArguments: [dict]) } func showDialog(_ title: String, message: String) { let alert = UIAlertController(title: title, message: message, preferredStyle: .alert) alert.addAction(UIAlertAction(title: "肯定", style: .default, handler: nil)) controller?.present(alert, animated: true, completion: nil) } }
而後在VC中的webview中代理方法中注入模型github
//webview代理中,綁定原生協議方法 func webViewDidFinishLoad(_ webView: UIWebView) { pp_jsContext = webView.value(forKeyPath: "documentView.webView.mainFrame.javaScriptContext") as! JSContext let model = javaScriptModel() model.controller = self model.jsContext = pp_jsContext // 這一步是將SwiftJavaScriptModel模型注入到JS中,在JS就能夠經過WebViewJSBridge調用咱們暴露的方法了。 pp_jsContext.setObject(model, forKeyedSubscript: "WebViewJSBridge" as (NSCopying & NSObjectProtocol)!) // pp_jsContext.exceptionHandler = { (context, exception) in //打印異常 print("exception:", exception) } }
到這裏基本上完成了,有不足的地方歡迎指正。web