第四天2018-10-24

switf原生与html.js交互

目的:实现点击更换图片的功能
原理:点击->js调用原生方法->在原生的方法里面传一个图片给js

关于原生与js交互就两点
1、原生调用js switf -> js
2、js调用原生 js -> switf

先把代码贴出来(copy代码前请看清楚下面的提示)

import UIKit

import JavaScriptCore

@objc protocol JSProtocol : JSExport {
    func face()
}

@objc class JSModel: NSObject ,JSProtocol {
    
    var view : ViewController?
    
    var context:JSContext!
    
    func face() {
        
        DispatchQueue.main.async {
            print("face")
            self.view?.callJs(funcName: "userFaceImg" , parameter: self.baseImage(image: UIImage.init(named: "1")! as UIImage));
        }
        
    }
    
    func baseImage(image : UIImage) -> String {
        
        return "'data:image/png;base64," + (UIImagePNGRepresentation(image)?.base64EncodedString(options: Data.Base64EncodingOptions(rawValue: 1)).replacingOccurrences(of: "\n", with: "").replacingOccurrences(of: "\r", with: ""))! as String + "'"
    }
    
}

class ViewController: UIViewController ,UIWebViewDelegate {
    
    var webView : UIWebView?
    
    var JSPush : NSString?
    
    var context : JSContext?
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        JSPush = "documentView.webView.mainFrame.javaScriptContext"

        webView = UIWebView(frame: self.view.bounds);
        
        webView?.scrollView.bounces = false;
        
        webView?.delegate = self as UIWebViewDelegate;
        
        self.view.addSubview(webView!);
        
        webView?.loadRequest(NSURLRequest.init(url: URL.init(string: "http://192.168.1.10:")! as URL) as URLRequest);
        
    }
    
    func webViewDidFinishLoad(_ webView: UIWebView) {
        
        context = webView.value(forKeyPath: JSPush! as String) as? JSContext;
        
        let model = JSModel()
        
        model.context = context;
        
        model.view = self
        
        context?.setObject(model, forKeyedSubscript: "js" as NSCopying & NSObjectProtocol)
        
        
    }
    
    func callJs(funcName : String , parameter : String){
        var context : JSContext?
        
        context = webView?.value(forKeyPath: JSPush! as String) as? JSContext;
        
        context!.evaluateScript(funcName + "(" + parameter + ")")
        
    }
    
    
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }


}

详细步骤:
1、添加webView。
2、webView用webViewDidFinishLoad方法获取原生方法
3、利用model将方法存入
4、setObject把方法和js的方法对接上
5、js调用原生
6、原生调用js

注意点:
①本文中的"js"是和前端对接后的命名!!!
②"http://192.168.1.10:"这是html链接!!!
③@objc因为一些机制问题需要添加!!!
④model 里的 view 是用来调用ViewController里面的callJs这个方法!!!

你可能感兴趣的:(第四天2018-10-24)