Swift version of WebViewJavascriptBridge with more simplified, friendly methods to send messages between Swift and JS in WKWebViews.
If your Swift version is below 3.0, Please use tag 0.1.5
release!
-
Add these lines below to your Podfile
platform :ios, '8.0' use_frameworks! pod 'SwiftWebViewBridge', '~> 0.3.0'
-
Install the pod by running
pod install
-
import SwiftWebViewBridge
Drag SwiftWebViewBridge.swift
file to your project.
- Xcode7.0+
- iOS7.0+
SwiftyJSON: SwiftyJSON makes it easy to deal with JSON data in Swift.
The communication between Swift and JS depends on JSON messages.The param jsonData you got in closure is deserlized by method below.You could simply pass it in JSON(jsonObject) designated initializer of SwiftJSON
NSJSONSerialization.JSONObjectWithData(serilizedData, .AllowFragments)
func JSONObjectWithData(_ data: NSData, options opt: NSJSONReadingOptions) throws -> AnyObject
- initialize a bridge with defaultHandler
- register handlers to handle different events
- send data / call handler on both sides
Generate a bridge with associated webView and default handler to deal with messages from js without specifying designated handler
let bridge = SwiftJavaScriptBridge.bridge(webView, defaultHandler: { data, responseCallback in
print("Swift received message from JS: \(data)")
responseCallback("Swift already got your msg, thanks")
})
Register a handler for JavaScript calling
// take care of retain cycle!
bridge.registerHandlerForJS(handlerName: "getSesionId", handler: { [unowned self] data, responseCallback in
let sid = self.session
responseCallback(["msg": "Swift has already finished its handler", "returnValue": [1, 2, 3]])
})
Simply Sent data to JS
bridge.sendDataToJS(["msg": "Hello JavaScript", "gift": ["100CNY", "1000CNY", "10000CNY"]])
Send data to JS with callback closure
bridge.sendDataToJS("Did you received my gift, JS?", responseCallback: { data in
print("Receiving JS return gift: \(data)")
})
func callJSHandler(_ handlerName: String?, params: SWVBData?, responseCallback: SWVBResponseCallBack?)
Call JavaScript registered handler
bridge.callJSHandler("alertReceivedParmas", params: ["msg": "JS, are you there?"], responseCallback: nil)
/// 1st param: responseData to JS
public typealias SWVBResponseCallBack = (NSDictionary) -> Void
/// 1st param: jsonData sent from JS; 2nd param: responseCallback for sending data back to JS
public typealias SWVBHandler = (AnyObject, @escaping SWVBResponseCallBack) -> Void
public typealias SWVBData = [String: Any]
SwiftWebViewBridge.logging = false //default true
bridge.init(function(message, responseCallback) {
log('JS got a message', message)
var data = { 'JS Responds' : 'Message received = )' }
responseCallback(data)
})
bridge.registerHandlerForSwift('alertReceivedParmas', function(data, responseCallback) {
log('ObjC called alertPassinParmas with', JSON.stringify(data))
alert(JSON.stringify(data))
var responseData = { 'JS Responds' : 'alert triggered' }
responseCallback(responseData)
})
bridge.sendDataToSwift('Say Hello Swiftly to Swift')
bridge.sendDataToSwift('Hi, anybody there?', function(responseData){
alert("got your response: " + JSON.stringify(responseData))
})
SwiftWebViewBridge.callSwiftHandler("printReceivedParmas", {"name": "小明", "age": "6", "school": "GDUT"}, function(responseData){
log('JS got responds from Swift: ', responseData)
})
The source code have very detailed comments, this will help you to dig it up if you are interesting in how swift and javascript communicate with each other. What's more, you can find the unminified javascript file in UnminifiedJavascript document.