js调用iOS代码
1、iOS定义方法
config.userContentController.add(self, name: "iOSSavePhoto")
2、实现方法
func userContentController(_ userContentController: WKUserContentController, didReceive message: WKScriptMessage) {
if message.name == "iOSSavePhoto" { // 保存图片
guard let data = try? Data.init(contentsOf: URL.init(string: (message.body as! String))!)
else { return }
let img = UIImage.init(data: data)
UIImageWriteToSavedPhotosAlbum(img!, self, #selector(image(image:didFinishSavingWithError:contextInfo:)), nil)
}
}
3、js端实现方法
window.webkit.messageHandlers.iOSSavePhoto.postMessage("url")
js给iOS传参数
1、单个参数
// js 端
window.webkit.messageHandlers.callbackHandle.postMessage("url")
// iOS端
func userContentController(_ userContentController: WKUserContentController, didReceive message: WKScriptMessage) {
let url: String = message.body as String
}
注意:如果js端定义的方法没有参数,也需要传postMessage(""),否则报错。提示缺少参数。
2、多个参数
// js 端
webkit.messageHandlers.callbackHandle2.postMessage({"name": "张三", "age": "12",})
// iOS端
func userContentController(_ userContentController: WKUserContentController, didReceive message: WKScriptMessage) {
let dic = message.body as? Dictionary
let name: String = (dic["name"] as AnyObject).description
let age: String = (dic["age"] as AnyObject).description
}
iOS调用js
1、iOS 端实现
webView.evaluateJavaScript("iOSSavePhotoCallback()", completionHandler: {
(any, error) in
})
示例:
// 保存图片完成
@objc func image(image:UIImage,didFinishSavingWithError error:NSError?,contextInfo:AnyObject) {
let result = error == nil ? true : false
let jsString = "iOSSavePhotoCallback('\(result)')"
self.webView.evaluateJavaScript(jsString, completionHandler: nil)
}
2、js端实现方法
function iOSSavePhotoCallback() {
}