swift -> WKWebView 或 UIWebView 和 JS 进行交互

阅读更多

参考: https://00red.com/blog/2016/03/22/teacher-swift-uiwebview-javascript/

 

 

一, JS 触发 SWIFT 

swift 代码

import UIKit
import JavaScriptCore

class ViewController: UIViewController,UIWebViewDelegate {

    
    var webView: UIWebView!
    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
        let path = Bundle.main.path(forResource: "test", ofType: "html")
        let url = NSURL(fileURLWithPath: path!)
        let request = NSURLRequest(url: url as URL)
        webView = UIWebView(frame: self.view.frame)        
        webView.loadRequest(request as URLRequest)
        self.view.addSubview(webView);
        //
        let jsContext = self.webView.value(forKeyPath: "documentView.webView.mainFrame.javaScriptContext") as? JSContext
        jsContext?.setObject(JavaScriptMethod(), forKeyedSubscript: "callSwift" as (NSCopying & NSObjectProtocol)!)
        
        
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    
    
  
}

//必须加前面的@objc
@objc protocol JavaScriptMethodProtocol: JSExport {
    //参数前面必须写上_下划线
    func postContent(_ value: String, _ number: String)
    func postContent2(_ value: String)
}

class JavaScriptMethod : NSObject, JavaScriptMethodProtocol {
    
    func postContent(_ value: String, _ number: String) {
        //方法名postContent
        print("dd"+value);
    }
    func postContent2(_ value: String){
        print("str:"+value);
    }
    
    
}

 

test.html


    
    
        

 

html 和SWIFT 文件在同一个目录

 

2 : 第二种通过 消息 通知的 形式 

先是swift 

 

import UIKit
import Foundation
import JavaScriptCore
import WebKit;

class Page1: UIViewController,WKScriptMessageHandler{
 
    override func viewDidLoad() {
        super.viewDidLoad()
        let conf = WKWebViewConfiguration()
        conf.userContentController.add(self as! WKScriptMessageHandler, name: "NOTIFY")
        let web  = WKWebView(frame: self.view.frame, configuration: conf)

        self.view.addSubview(web)
        let url:String = "http://192.168.2.188/9/2.php"
        web.load(NSURLRequest(url: NSURL(string: url) as! URL) as URLRequest);
        
        
    }
    func userContentController(_ userContentController: WKUserContentController, didReceive message: WKScriptMessage) {
        if message.name == "NOTIFY" {
            if let dic = message.body as? NSDictionary {
                print(dic["link"])
                print(dic["image"])
            }
        }
    }
}
 

 

然后 php 文件里的JS 通过如下JS 代码触发

var data = {};
data.link = "aaa";
data.image = "iiiii";
webkit.messageHandlers.NOTIFY.postMessage(data);

 

 

二、swift 触发 js

 

在上面的html  中增加 JS 代码

    

 

在上面的swift 中增加代码

self.webView.stringByEvaluatingJavaScript(from: "doFun('你执行了DOFUN')")

 

其中 执行JS 代码 需要等HTML 加载完,可通过代理监控事件判断 

 

另: 如果存在 300毫秒点击延迟可 改用 WKWebView 并 在html 的meta 中设置 user-scalable=0 

 

 

 ** swift 通过执行 js 返回 执行 结果 ,比如 通过JS 的方法 获取页面的title 

    func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
   
        //要执行的js 语句
        let script:String = "document.title";
        webView.evaluateJavaScript(script, completionHandler: { (result, error) in
            if result != nil {
                print("通过evaluateJavaScript获取的结果:"+(result as! String));
                //结果就是打印出了该站的title 不过是通过js 的方法
            } else {
                print(error ?? "Error")
            }
        })
        
    }

 

 相关参考: 根据某个标签的属性值获取另外一个属性值

http://mft.iteye.com/admin/blogs/2378327

 

你可能感兴趣的:(webview)