載入本地HTML檔案
xoverride func loadView() {
super.loadView()
let conf = WKWebViewConfiguration()
//JS呼叫HTML時使用的name
conf.userContentController.add(self, name: "wkbridge")
self.wk = WKWebView(frame: CGRect(x: 0, y:20, width: self.view.frame.size.width, height: self.view.frame.size.height - 20), configuration: conf)
self.wk.navigationDelegate = self
self.wk.uiDelegate = self
if let path = Bundle.main.path(forResource: "index", ofType: "html", inDirectory: "www") {
let fileUrl = URL(fileURLWithPath: path)
self.wk.loadFileURL(fileUrl, allowingReadAccessTo: fileUrl)
}
//每個頁面注入 JS 外掛程式碼 (runPluginJS方法在下面)
self.runPluginJS(names: ["Base", "Console", "Sandbox"])
//注入頁面間傳遞的引數
if pageParam != nil {
self.wk.evaluateJavaScript("win.pageParam=\(pageParam!)", completionHandler: nil)
}
self.view.addSubview(self.wk)
//新增一個等待指示器
self.view.backgroundColor = UIColor.white
activityIndicator = UIActivityIndicatorView()
activityIndicator.center = CGPoint(x: self.view.bounds.width/2, y: self.view.bounds.height/2)
activityIndicator.color = UIColor.black
activityIndicator.startAnimating()
self.view.addSubview(activityIndicator)}//注入外掛檔案func runPluginJS(names: Array<String>) {
for name in names {
if let path = Bundle.main.path(forResource: name, ofType: "js") {
do {
let js = try NSString(contentsOfFile: path, encoding: String.Encoding.utf8.rawValue)
self.wk.evaluateJavaScript(js as String, completionHandler: nil)
} catch let error as NSError {
print(error.debugDescription)
}
}
}}
在專案根目錄中新建 www 資料夾(自定義) 放入 html js css 圖片 檔案,前端檔案都放在www中,方便管理
注意
將wkwebview需要訪問的本地檔案 新增到專案的 Bundle Resources
HTML 與 Native 互動
ViewController 實現 三個協議 WKNavigationDelegate, WKUIDelegate, WKScriptMessageHandler
JS呼叫Swift程式碼
js直接使用
xxxxxxxxxx
// wkbridge為在WKWebViewConfiguration定定義的name
// js傳遞的param使用json物件 ,比如類似{className: "Console", functionName: "log", data: {msg: "來自js的console"}}
window.webkit.messageHandlers.wkbridge.postMessage(param);
會觸發swift方法
xxxxxxxxxxfunc userContentController(_ userContentController: WKUserContentController, didReceive message: WKScriptMessage) {
if message.name == "wkbridge" {
if let dic = message.body as? NSDictionary,
let className = (dic["className"] as AnyObject).description,
let functionName = (dic["functionName"] as AnyObject).description {
if let cls = NSClassFromString((Bundle.main.object(forInfoDictionaryKey: "CFBundleName")! as AnyObject).description + "." + className) as? Plugin.Type{
let obj = cls.init()
obj.viewController = self
obj.wk = self.wk
obj.taskId = (dic["taskId"] as AnyObject).integerValue
obj.data = (dic["data"] as AnyObject) as? NSDictionary
let functionSelector = Selector(functionName)
if obj.responds(to: functionSelector) {
obj.perform(functionSelector)
} else {
print("Undefined function :\(functionName)")
}
} else {
print("Class Not Found: \(className)")
}
}
}}
js的方法在 Xcode的控制檯列印內容
在swift新建類Console.swift
xxxxxxxxxximport UIKitclass Console: Plugin {
func log() {
if let string = self.data?["msg"] {
print(string)
}
}}
這裡使用到一個基類 Plugin 用來處理 js 與 swift的互動
xxxxxxxxxximport UIKitimport WebKitclass Plugin: NSObject {
var viewController: MeiWebView!
var wk: WKWebView!
var taskId: Int!
var data: NSDictionary?
required override init() {
}
func callback(values: NSDictionary) -> Bool {
do {
let jsonData = try JSONSerialization.data(withJSONObject: values, options: JSONSerialization.WritingOptions())
if let jsonString = NSString(data: jsonData, encoding: String.Encoding.utf8.rawValue) as? String,
let tTaskId = self.taskId{
let js = "fireTask(\(tTaskId), '\(jsonString)');"
self.wk.evaluateJavaScript(js, completionHandler: nil)
return true
}
} catch let error as NSError{
NSLog(error.debugDescription)
return false
}
return false
}
func errorCallback(errorMessage: String) {
let js = "onError(\(self.taskId), '\(errorMessage)');"
self.wk.evaluateJavaScript(js, completionHandler: nil)
}
func convertToDictionary(text: String) -> [String: Any]? {
if let data = text.data(using: .utf8) {
do {
print(text)
print(data)
return try JSONSerialization.jsonObject(with: data, options: []) as? [String: Any]
} catch {
print("JSON 轉換失敗 :" + error.localizedDescription)
}
}
return nil
} }
這樣js的方法就會在 Xcode的控制檯列印出 內容了
對於隱藏介面,給前段一個友好的方式,使用自定義JS檔案,使用上面的runJSPlugin直接寫入到html中,在runJSPlugin 方法中 用到的js檔案, 在專案中新建一個GROUP 統一管理,我覺得與www資料夾中的前端檔案分離比較好。方法使用陣列傳遞需要寫入的JS的名稱,這裡列出Console.js
xxxxxxxxxxvar console = {
log: function(message) { //console.log(msg);
window.webkit.messageHandlers.wkbridge.postMessage({className: "Console", functionName: "log", data: {msg: message}});
}};
這樣在js中只要執行 console.log() 就可以在Xcode控制檯列印內容了。
Swift介面回撥
js 層使用佇列管理, 新建Base.js
xxxxxxxxxx
Queue = [];function Task(id, callback, errorCallback) {
var mTask = new Object;
mTask.id = id;
mTask.callback = callback;
mTask.errorCallback = errorCallback;
mTask.once = false;
return mTask;}fireTask = function(i, j) {
if (typeof Queue[i].callback == 'function') {
Queue[i].callback(JSON.parse(j));
if (Queue[i].once) Queue[i] = null;
} };onError = function (i, j) {
Queue[i].errorCallback(j);};
實現獲取沙盒根目錄
Sandbox.swift
ximport UIKitclass Sandbox: Plugin {
func getRootPath() {
let path = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)[0]
let dic = NSDictionary.init(object: path.absoluteString, forKey: "rootPath" as NSCopying)
_ = callback(values: dic)
}}
新建 Sandbox.js
xxxxxxxxxx
Sandbox = {
getRootPath: function(onSuccess, onError) {
Queue.push(Task(Queue.length, onSuccess, onError));
window.webkit.messageHandlers.wkbridge.postMessage({className: "Finder", functionName: "getRootPath", taskId: Queue.length - 1});
},};
js中執行
xxxxxxxxxx
Sandbox.getRootPath(function(path){
console.log(path.rootPath); //獲取沙盒路徑})
Swift呼叫JS程式碼
xxxxxxxxxxlet js = "jsFunction(param);"self.wk.evaluateJavaScript(js, completionHandler: nil)
訪問沙盒檔案
將檔案轉換成base64的字串傳遞給js, src直接設定data。
WKWebView 只能讀取tmp中的檔案,所以將檔案寫入到 NSTemporaryDirectory() 的路徑下面就可以了,以後js需要訪問什麼檔案,將檔案複製到tmp資料夾就可以訪問了,按需刪除就好了。
推薦文章
來自 “ ITPUB部落格 ” ,連結:http://blog.itpub.net/69990324/viewspace-2741413/,如需轉載,請註明出處,否則將追究法律責任。