码迷,mamicode.com
首页 > 编程语言 > 详细

一步一步学习Swift之(四)玩转UIWebView

时间:2015-05-01 14:39:43      阅读:205      评论:0      收藏:0      [点我收藏+]

标签:

实现原理:

1.通过UIWebView的stringByEvaluatingJavaScriptFromString方法来触发脚本

2.通过自定义连接来触发oc代码

实现过程

@IBOutlet weak var webView: UIWebView!
    override func viewDidLoad() {
        super.viewDidLoad()
       webView.loadRequest(NSURLRequest(URL: NSURL(string: "http://passport.cnblogs.com/user/signin")!))
        webView.delegate=self
    }
    //连接改变时
    func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool{
       var rurl =  request.URL?.absoluteString
        if (rurl!.hasPrefix("ios:")){
          var method =  rurl!.componentsSeparatedByString("@")[1]
            if method == "signin_go"{
                 signin_go()
            }
            return false
        }
       return true
    }
    //加载完成时
    func webViewDidFinishLoad(webView: UIWebView){
        //注入脚本,这个脚本把登录方法js重写为连接
        var jsPath =  NSBundle.mainBundle().pathForResource("app", ofType: "js")
        var jsContent:NSString = NSString (contentsOfFile: jsPath!, encoding: 0, error: nil)!
        jsContent=jsContent.stringByReplacingOccurrencesOfString("\n", withString: "")
        webView.stringByEvaluatingJavaScriptFromString(jsContent as String)
    }
    
    func signin_go(){
    NSLog("-我执行了signin_go-")
    }
var script = document.createElement(script);
script.type = text/javascript;
script.text = function signin_go(){
   location.href="ios:@signin_go";
}
;
document.getElementsByTagName(head)[0].appendChild(script);

 

转载请注明来源:http://www.cnblogs.com/wuxian/p/4470634.html 

一步一步学习Swift之(四)玩转UIWebView

标签:

原文地址:http://www.cnblogs.com/wuxian/p/4470634.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!