在開發過程中,我們可能遇到ios代碼與js互動的情況,本人第一次使用遇到了很多坑,這裡紀錄一下,友善自己,也友善需要的人。
1.第一步先建一個接口(協定)并繼承JSExport
這裡實作兩個方法提供給js調用的方法
importJavaScriptCore
@objcprotocolSwiftJavaScriptDelegate:JSExport{
funcshow()
funcshowAlert(_str:String,_msg:String)
}
2.第二步需要寫一個類去實作上一步的接口(協定)(注意:1.這裡必須要繼承nsobject否則會報錯,2.如果要傳參數的話一定要寫成
類似與 funcshowAlert(_str:String,_msg:String),_ str:String 這個“_”一定要加不然無法調用(調用無效果),在swift3.0中就這樣,其他版本沒有測試就不清楚了。
)
@objcclassSwiftJavaScriptModel:NSObject,SwiftJavaScriptDelegate{
funcshow() {
print("js調用我了")
funcshowAlert(_str:String,_msg:String){
print("js調用我了:",str,msg)
3.開始在控制器中測試
//
//ViewController.swift
//WEBJSTest
//Created by admin on 17/8/5.
//Copyright © 2017年tdin360. All rights reserved.
importUIKit
importWebKit
classViewController:UIViewController,UIWebViewDelegate{
varcontext:JSContext!
overridefuncviewDidLoad() {
super.viewDidLoad()
self.setupUI()
funcsetupUI( ) {
self.view.addSubview(webView)
leturl =Bundle.main.path(forResource:"index", ofType:"html")
self.webView.loadRequest(URLRequest(url:URL(string:url!)!))
self.webView.delegate=self
self.view.addSubview(btn)
lazyvarwebView:UIWebView={
letwebView =UIWebView(frame:self.view.bounds)
returnwebView
}()
//用于點選調用js的按鈕
lazyvarbtn:UIButton={
letbtn =UIButton(frame:CGRect(x:0,y:300,width:100,height:40))
btn.backgroundColor=UIColor.blue
btn.setTitle("調用js", for: .normal)
btn.addTarget(self, action:#selector(onClick), for: .touchUpInside)
returnbtn
//swift調用js
funconClick(){
letf =context?.objectForKeyedSubscript("swift")
_=f?.call(withArguments: [["name":"admin","pass":"fdsfds"]])
funcwebViewDidFinishLoad(_webView:UIWebView) {
letmodel =SwiftJavaScriptModel()
//擷取context
context=self.webView.value(forKeyPath:"documentView.webView.mainFrame.javaScriptContext")as!JSContext
//這裡注冊一個标示給js通路
context.setObject(model, forKeyedSubscript:"model"as(NSCopying&NSObjectProtocol)!)
leturl =Bundle.main.url(forResource:"index", withExtension:"html")
context.evaluateScript(try?String(contentsOf: url!, encoding:String.Encoding.utf8))
context.exceptionHandler= {
(context, exception)in
print("exception錯誤@", exception ??"")
overridefuncdidReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
4.html代碼
<html>
<meta charset="utf-8">
<title>ios js互動測試</title>
<head>
<script>
//這個送出給swift調用并傳參數
function swift(obj){
alert("swift調用我了"+obj["name"]+"--"+obj["pass"]);
}
</script>
</head>
<body>
<button onclick="model.showAlert('參數1','參數2')">js調用swift有參的方法</button>
<button onclick="model.show()" >js調用swift無參數方法</button>
</body>
</html>
整個過程就是這樣的,這裡貼了源碼,如果遇到問題歡迎留言,有什麼更好的方法歡迎一起交流。