美文网首页
Swift之UIWebView

Swift之UIWebView

作者: 乡水情缘 | 来源:发表于2016-12-25 16:32 被阅读133次
     //webview
            self.web = UIWebView.init(frame: CGRect(x:0,y:0,width:SCREEN_WIDTH,height:SCREEN_HEIGHT));
    //加载网络链接
            self.web?.loadRequest(NSURLRequest(url: NSURL(string: "http://www.baidu.com")! as URL) as URLRequest)
    //加载本地HTML
    //        self.web?.loadRequest(NSURLRequest(url: NSURL.init(fileURLWithPath: Bundle.main.path(forResource: "AboutUs", ofType: "html")!) as URL) as URLRequest)
            self.view.addSubview(self.web!);
    
    //连接改变时
        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);
    

    相关文章

      网友评论

          本文标题:Swift之UIWebView

          本文链接:https://www.haomeiwen.com/subject/ifcdvttx.html