swift代码:
import UIKit
class ViewController: UIViewController, UIWebViewDelegate {
@IBOutlet weak var theWebView: UIWebView!
override func viewDidLoad() {
//加载本地html
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>