随着Hybrid APP的流行,需要我们研究下各类native和html页面互相调用的问题。网上OC的例子很多了,但是Swift的调用案例非常少,在这里写了一下。
一、首先,让我们写一个html页面
index.html
<script> function helloWorld(msg){ document.getElementById('message').innerHTML=msg; } function showIOSDialog(msg){ console.log("show iOS dialog"); var myJSONObject=new Object(); myJSONObject.title='iOS'; myJSONObject.content=msg; var JSONString=JSON.stringify(myJSONObject); var uri='gap://XXXClass.XXXmethod#'+JSONString; window.location=uri; } </script> <body> <h2>html javascript</h2> <div id="message"></div><br> <button onclick='showIOSDialog(" i am get from iOS")'>get from iOS</button> </body>
function helloWorld 是用于swift来进行调用的,目标是在index.html上输出一句话;
function showIOSDialog 用于调用swift的方法,目标是APP内打印出json信息;
var uri='gap://XXXClass.XXXmethod#'+JSONString; window.location=uri;
这是调用swift的重点,机制类似于向native发送一个消息,native解析出方法等参数,进行对应的处理即可,需要传递的信息放入jsongString内;
二、看看swift的代码
func webViewDidFinishLoad(webView: UIWebView!) {
println("webView did finish")
webView.stringByEvaluatingJavaScriptFromString("helloWorld('this is write from iOS')");
}
func webView(webView: UIWebView!, shouldStartLoadWithRequest request: NSURLRequest!, navigationType: UIWebViewNavigationType) -> Bool {
var actionType:NSString=request.URL.host!;
println("\(actionType)")
var scheme:NSString=request.URL.scheme!;
println("\(scheme)")
var fragment:NSString=""
//let fragment=request.URL.fragment!;
println("webView should start")
if(scheme=="gap"){
var fragment=request.URL.fragment!;
println("\(fragment)")
}
return true
}
func webViewDidFinishLoad通过
webView.stringByEvaluatingJavaScriptFromString("helloWorld('this is write from iOS')"),调用javascript内的方法,输出一句话;
func webView(webView: UIWebView!, shouldStartLoadWithRequest request: NSURLRequest!, navigationType: UIWebViewNavigationType) -> Bool {}
当js内的
window.location=uri;使用后,会触发这一消息,然后request.URL.host!;
request.URL.scheme!;
request.URL.fragment!;
分别解析出请求的host、协议、附加的string信息,即可!