Swift与JavaScript交互

Swift版本WebViewJavascriptBridge—SwiftWebViewBridge

For Swift

Generate a bridge with associated webView and default handler to deal with messages from js

 public class func bridge(webView: UIWebView, defaultHandler handler: SWVBHandler?) -> SwiftWebViewBridge

Generate a bridge with associated webView and default handler to deal with messages from js without specifying designated handler

        self.bridge = SwiftWebViewBridge.bridge(webView, defaultHandler: { data, responseCallback in
            
            print("Swift received message from JS: \(data)")
            
            // Actually, this responseCallback could be an empty closure when javascript has no callback, saving you from unwarping an optional parameter = )
            responseCallback("Swift already got your msg, thanks")
        })

Register a handler for JavaScript calling

      self.bridge.registerHandlerForJS(handlerName: "printReceivedParmas", handler: { [unowned self] jsonData, responseCallback in
            
            // if you used self in any bridge handler/callback closure, remember to declare weak or unowned self, preventing from retaining cycle!
            // Because VC owned bridge, brige owned this closure, and this cloure captured self!
            self.printReceivedParmas(jsonData)
            
            responseCallback(["msg": "Swift has already finished its handler", "returnValue": [1, 2, 3]])
            })

调用js方法

    private func printReceivedParmas(data: AnyObject) {
        
        print("Swift recieved data passed from JS: \(data)")
    }

Sent data to JS simply

self.bridge.sendDataToJS(["msg": "Hello JavaScript, My name is 小明", "gift": ["100CNY", "1000CNY", "10000CNY"]])

你可能感兴趣的:(Swift与JavaScript交互)