Git Product home page Git Product logo

swiftwebviewbridge's Introduction

SwiftWebViewBridge

ObjC ObjC pod

Swift version of WebViewJavascriptBridge with more simplified, friendly methods to send messages between Swift and JS in UIWebViews.


  1. Preview
  2. Requirements
  3. Installation
  4. How to use it
  5. Dig it up

Preview

preview preview2

Requirements

  1. Xcode7.0+
  2. iOS7.0+

####Optional

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

Installation

####Cocoapods(iOS8+)

  1. Add these lines below to your Podfile

    platform :ios, '8.0'
    use_frameworks!	
    pod 'SwiftWebViewBridge', '~> 0.1.3'
    
  2. Install the pod by running pod install

  3. import SwiftWebViewBridge

####Manually(iOS7+)

Drag SwiftWebViewBridge.swift file to your project.

How to use it:

###General

  1. initialize a bridge with defaultHandler
  2. register handlers to handle different events
  3. send data / call handler on both sides

###For Swift

#####func bridge(webView: UIWebView, defaultHandler handler: SWVBHandler?) -> SwiftJavaScriptBridge? Generate a bridge with associated webView and default handler to deal with messages from js without specifying designated handler

let brige = SwiftJavaScriptBridge.bridge(webView, defaultHandler: { data, responseCallback in
	print("Swift received message from JS: \(data)")
	responseCallback("Swift already got your msg, thanks")
}) 

#####func registerHandlerForJS(handlerName name: String, handler:SWVBHandler) 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]])
})

#####func sendDataToJS(data: AnyObject) Simply Sent data to JS

bridge.sendDataToJS(["msg": "Hello JavaScript", "gift": ["100CNY", "1000CNY", "10000CNY"]])

#####func sendDataToJS(data: AnyObject, responseCallback: SWVBResponseCallBack?) 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: AnyObject?, responseCallback: SWVBResponseCallBack?) Call JavaScript registered handler

bridge.callJSHandler("alertReceivedParmas", params: ["msg": "JS, are you there?"], responseCallback: nil)

#####two custom closures mentioned above

/// 1st param: responseData to JS
public typealias SWVBResponseCallBack = AnyObject -> Void
/// 1st param: jsonData sent from JS; 2nd param: responseCallback for sending data back to JS
public typealias SWVBHandler = (AnyObject, SWVBResponseCallBack) -> Void

#####logging for debug

SwiftWebViewBridge.logging = false  //default true

###For JavaScript

#####function init(defaultHandler)

bridge.init(function(message, responseCallback) {
	log('JS got a message', message)
	var data = { 'JS Responds' : 'Message received = )' }
	responseCallback(data)
})

#####function registerHandlerForSwift(handlerName, handler)

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)
})

#####function sendDataToSwift(data, responseCallback)

bridge.sendDataToSwift('Say Hello Swiftly to Swift')
bridge.sendDataToSwift('Hi, anybody there?', function(responseData){
	alert("got your response: " + JSON.stringify(responseData))
})

#####function callSwiftHandler(handlerName, data, responseCallback)

SwiftWebViewBridge.callSwiftHandler("printReceivedParmas", {"name": "小明", "age": "6", "school": "GDUT"}, function(responseData){
	log('JS got responds from Swift: ', responseData)
})

Dig it up

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.

swiftwebviewbridge's People

Contributors

shawnfoo avatar

Watchers

James Cloos avatar peterwang avatar  avatar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.