首發:我的博客,更新&糾錯&回覆javascript
1.本地語言調js的方式與android中的方式相似,也是向WebView控件發送要調用的js語句html
2. 但js調本地語言,則不是像android那樣直接調一個全局變量的方法,而是經過location.href=xx://yy這樣的方式觸發UIWebViewDelegate接口實現者的webView shouldStartLoadWithRequest navigationType方法,該方法應該判斷目標路徑(即xx://yy)的schema(即xx)是否實際是要調用swift,若是是,則按約定執行之,並返回false阻止網頁路徑變化,若是不是要調用swift,則返回true,讓改網頁繼續正常加載目標url。java
android和iOS對比,它們都用了僞url的技術,但android是在本地語言調js時使用了僞url(該url的schema爲javascript),而iOS是js調本地語言時使用了僞url(該url是自定義的標識),這個錯落頗有意思。android
swift代碼:web
import UIKitswift
class ViewController: UIViewController, UIWebViewDelegate {ide
@IBOutlet weak var theWebView: UIWebView!lua
override func viewDidLoad() {url
//加載本地htmlspa
let res = NSBundle.mainBundle().pathForResource("index",ofType:"html")
let url = NSURL(fileURLWithPath: res!);
let request = NSURLRequest(URL: url);
self.theWebView.loadRequest(request);
self.theWebView.delegate = self;
}
//讓js能夠調用swift
func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
//判斷是否是js在調用swift,若是是,則處理並返回false
if(request.URL!.scheme == "myschema"){
let host = request.URL!.host;
if(host == "go"){
let query = request.URL!.query!;
print(query);
let split = query.componentsSeparatedByString("=");
let text = split[1];
self.theWebView.stringByEvaluatingJavaScriptFromString("changeContent(\"" + text + "\")");
}
return false;
}else{
return true;
}
}
//swift調用js
@IBAction func btnClicked(sender: AnyObject) {
self.theWebView.stringByEvaluatingJavaScriptFromString("changeContent(\"123\")");
}
}
網頁代碼:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
</head>
<body>
<span id="theSpan"></span>
<button onclick="doIt()">js調用swift</button>
<input type="text" id="t">
<script>
//讓swift能夠調用js
function changeContent(str){
document.getElementById('theSpan').innerHTML = str;
}
//js調用swift
function doIt(){
document.location.href = "myschema://go?a=" + document.getElementById("t").value;
}
</script>
</body>
</html>