WVJSB 1.0.1

WVJSB 1.0.1

Maintained by retriable.



WVJSB 1.0.1

  • By
  • retriable

WVJSB

License MIT Build Status Carthage compatible Pod Version Pod Platform

Cross-iframe WebView JavaScript Bridge.

Installation

Native

Cocoapods

Add the following to your project's Podfile:

pod 'WVJSB'

Carthage

Add the following to your project's Cartfile:

github "retriable/WVJSB"

Web

Add JavaScript to web project.

Native usage

Create server

Server is automatically associated with the web view.

    WVJSBServer *server=[WVJSBServer serverWithWebView:webView namespace:@"server namespace"];

Handle unresponsive request

[[server on:@"method"] onEvent:^id(WVJSBConnection * connection, id parameter, WVJSBAckBlock (^done)(void)) {
    done();
    return nil;
}];

Handle responsive request

[[server on:@"request"] onEvent:^id(WVJSBConnection * connection, id parameter, WVJSBAckBlock (^done)(void)) {
    done()(@"response object",nil);
    return nil;
}];

Handle cancelable request

[[[server on:@"request"] onEvent:^id (WVJSBConnection * connection, id parameter, WVJSBAckBlock (^done)(void)) {
    //Simulate asynchronous request
    dispatch_source_t timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, dispatch_get_main_queue());
    dispatch_source_set_timer(timer, dispatch_time(DISPATCH_TIME_NOW, NSEC_PER_SEC*2), DBL_MAX, 0 * NSEC_PER_SEC);
    dispatch_source_set_event_handler(timer, ^{
        done()(@"response object",nil);
    });
    dispatch_resume(timer);
    //Return the timer as context 
    return timer;
}] onCancel:^(id  context) {
    dispatch_source_t timer = context;
    //Cancel timer 
    dispatch_source_cancel(timer);
}];

Request to JavaScript client

WVJSBConnection *connection =  server.connections.allValues.lastObject;
WVJSBOperation *operation = [[[connection event:@"request" parameter:nil] onAck:^(WVJSBOperation *operation,id result, NSError *error) {
    //Do something with result
}] timeout:30];

Cancel request

[operation cancel];

JavaScript usage

Create client

const client = WVJSBClient('server namespace',{"key":"value"});

Handle unresponsive request

client.on('method').onEvent(function(parameter,done){
    done();
})

Handle responsive request

client.on('request').onEvent(function(parameter,done){
    done()('response object',null);
})

Handle cancelable request

client.on('request').onEvent(function(parameter,done){
    const context = window.setTimeout(function(){
        done()('response object',null);
    },2000);
    return context;
}).onCancel(function(context){
    window.clearTimeout(context);
});

Request to native server

const operation = client.event('request',null).onAck(function(operation,parameter,error){

}).timeout(30000);

Cancel request

operation.cancel();

Run Example

Open Terminal,and execute following

cd pathToProject/WVJSB/Resources/www
python -m SimpleHTTPServer

Then open project and run