Skip to content

Commit

Permalink
Using Base class in UIWebView
Browse files Browse the repository at this point in the history
  • Loading branch information
lokimeyburg committed Nov 8, 2014
1 parent b318263 commit 589dc2a
Show file tree
Hide file tree
Showing 5 changed files with 36 additions and 185 deletions.
5 changes: 1 addition & 4 deletions WebViewJavascriptBridge/WKWebViewJavascriptBridge.h
Original file line number Diff line number Diff line change
Expand Up @@ -12,8 +12,8 @@
#if defined(supportsWKWebKit )

#import <Foundation/Foundation.h>

#import <WebKit/WebKit.h>

typedef void (^WVJBResponseCallback)(id responseData);
typedef void (^WVJBHandler)(id data, WVJBResponseCallback responseCallback);

Expand All @@ -32,9 +32,6 @@ typedef void (^WVJBHandler)(id data, WVJBResponseCallback responseCallback);
- (void)callHandler:(NSString*)handlerName data:(id)data responseCallback:(WVJBResponseCallback)responseCallback;
- (void)reset;

// delegate method
- (void) _evaluateJavascript:(NSString*)javascriptCommand;

@end

#endif
6 changes: 3 additions & 3 deletions WebViewJavascriptBridge/WKWebViewJavascriptBridge.m
Original file line number Diff line number Diff line change
Expand Up @@ -18,8 +18,6 @@ @implementation WKWebViewJavascriptBridge {
WebViewJavascriptBridgeBase *_base;
}

//@synthesize delegate;

/* API
*****/

Expand Down Expand Up @@ -165,9 +163,11 @@ - (void)webView:(WKWebView *)webView
}
}

- (void) _evaluateJavascript:(NSString*)javascriptCommand
- (NSString*) _evaluateJavascript:(NSString*)javascriptCommand
{
NSLog(@"----- EVALUATING");
[_webView evaluateJavaScript:javascriptCommand completionHandler:nil];
return NULL;
}


Expand Down
189 changes: 19 additions & 170 deletions WebViewJavascriptBridge/WebViewJavascriptBridge.m
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
//

#import "WebViewJavascriptBridge.h"
#import "WebViewJavascriptBridgeBase.h"

#if __has_feature(objc_arc_weak)
#define WVJB_WEAK __weak
Expand All @@ -19,14 +20,8 @@
@implementation WebViewJavascriptBridge {
WVJB_WEAK WVJB_WEBVIEW_TYPE* _webView;
WVJB_WEAK id _webViewDelegate;
NSMutableArray* _startupMessageQueue;
NSMutableDictionary* _responseCallbacks;
NSMutableDictionary* _messageHandlers;
long _uniqueId;
WVJBHandler _messageHandler;

NSBundle *_resourceBundle;

WebViewJavascriptBridgeBase *_base;
#if defined WVJB_PLATFORM_IOS
NSUInteger _numRequestsLoading;
#endif
Expand All @@ -36,8 +31,7 @@ @implementation WebViewJavascriptBridge {
/* API
*****/

static bool logging = false;
+ (void)enableLogging { logging = true; }
+ (void)enableLogging { [WebViewJavascriptBridgeBase enableLogging]; }

+ (instancetype)bridgeForWebView:(WVJB_WEBVIEW_TYPE*)webView handler:(WVJBHandler)handler {
return [self bridgeForWebView:webView webViewDelegate:nil handler:handler];
Expand All @@ -59,7 +53,7 @@ - (void)send:(id)data {
}

- (void)send:(id)data responseCallback:(WVJBResponseCallback)responseCallback {
[self _sendData:data responseCallback:responseCallback handlerName:nil];
[_base _sendData:data responseCallback:responseCallback handlerName:nil];
}

- (void)callHandler:(NSString *)handlerName {
Expand All @@ -71,162 +65,28 @@ - (void)callHandler:(NSString *)handlerName data:(id)data {
}

- (void)callHandler:(NSString *)handlerName data:(id)data responseCallback:(WVJBResponseCallback)responseCallback {
[self _sendData:data responseCallback:responseCallback handlerName:handlerName];
[_base _sendData:data responseCallback:responseCallback handlerName:handlerName];
}

- (void)registerHandler:(NSString *)handlerName handler:(WVJBHandler)handler {
_messageHandlers[handlerName] = [handler copy];
_base.messageHandlers[handlerName] = [handler copy];
}

/* Platform agnostic internals
*****************************/

- (id)init {
if (self = [super init]) {
_startupMessageQueue = [NSMutableArray array];
_responseCallbacks = [NSMutableDictionary dictionary];
_uniqueId = 0;
}
return self;
}

- (void)dealloc {
[self _platformSpecificDealloc];

_base = nil;
_webView = nil;
_webViewDelegate = nil;
_startupMessageQueue = nil;
_responseCallbacks = nil;
_messageHandlers = nil;
_messageHandler = nil;
}

- (void)_sendData:(id)data responseCallback:(WVJBResponseCallback)responseCallback handlerName:(NSString*)handlerName {
NSMutableDictionary* message = [NSMutableDictionary dictionary];

if (data) {
message[@"data"] = data;
}

if (responseCallback) {
NSString* callbackId = [NSString stringWithFormat:@"objc_cb_%ld", ++_uniqueId];
_responseCallbacks[callbackId] = [responseCallback copy];
message[@"callbackId"] = callbackId;
}

if (handlerName) {
message[@"handlerName"] = handlerName;
}
[self _queueMessage:message];
}

- (void)_queueMessage:(WVJBMessage*)message {
if (_startupMessageQueue) {
[_startupMessageQueue addObject:message];
} else {
[self _dispatchMessage:message];
}
}

- (void)_dispatchMessage:(WVJBMessage*)message {
NSString *messageJSON = [self _serializeMessage:message];
[self _log:@"SEND" json:messageJSON];
messageJSON = [messageJSON stringByReplacingOccurrencesOfString:@"\\" withString:@"\\\\"];
messageJSON = [messageJSON stringByReplacingOccurrencesOfString:@"\"" withString:@"\\\""];
messageJSON = [messageJSON stringByReplacingOccurrencesOfString:@"\'" withString:@"\\\'"];
messageJSON = [messageJSON stringByReplacingOccurrencesOfString:@"\n" withString:@"\\n"];
messageJSON = [messageJSON stringByReplacingOccurrencesOfString:@"\r" withString:@"\\r"];
messageJSON = [messageJSON stringByReplacingOccurrencesOfString:@"\f" withString:@"\\f"];
messageJSON = [messageJSON stringByReplacingOccurrencesOfString:@"\u2028" withString:@"\\u2028"];
messageJSON = [messageJSON stringByReplacingOccurrencesOfString:@"\u2029" withString:@"\\u2029"];

NSString* javascriptCommand = [NSString stringWithFormat:@"WebViewJavascriptBridge._handleMessageFromObjC('%@');", messageJSON];
if ([[NSThread currentThread] isMainThread]) {
[_webView stringByEvaluatingJavaScriptFromString:javascriptCommand];
} else {
__strong WVJB_WEBVIEW_TYPE* strongWebView = _webView;
dispatch_sync(dispatch_get_main_queue(), ^{
[strongWebView stringByEvaluatingJavaScriptFromString:javascriptCommand];
});
}
}

- (void)_flushMessageQueue {
NSString *messageQueueString = [_webView stringByEvaluatingJavaScriptFromString:@"WebViewJavascriptBridge._fetchQueue();"];

id messages = [self _deserializeMessageJSON:messageQueueString];
if (![messages isKindOfClass:[NSArray class]]) {
NSLog(@"WebViewJavascriptBridge: WARNING: Invalid %@ received: %@", [messages class], messages);
return;
}
for (WVJBMessage* message in messages) {
if (![message isKindOfClass:[WVJBMessage class]]) {
NSLog(@"WebViewJavascriptBridge: WARNING: Invalid %@ received: %@", [message class], message);
continue;
}
[self _log:@"RCVD" json:message];

NSString* responseId = message[@"responseId"];
if (responseId) {
WVJBResponseCallback responseCallback = _responseCallbacks[responseId];
responseCallback(message[@"responseData"]);
[_responseCallbacks removeObjectForKey:responseId];
} else {
WVJBResponseCallback responseCallback = NULL;
NSString* callbackId = message[@"callbackId"];
if (callbackId) {
responseCallback = ^(id responseData) {
if (responseData == nil) {
responseData = [NSNull null];
}

WVJBMessage* msg = @{ @"responseId":callbackId, @"responseData":responseData };
[self _queueMessage:msg];
};
} else {
responseCallback = ^(id ignoreResponseData) {
// Do nothing
};
}

WVJBHandler handler;
if (message[@"handlerName"]) {
handler = _messageHandlers[message[@"handlerName"]];
} else {
handler = _messageHandler;
}

if (!handler) {
[NSException raise:@"WVJBNoHandlerException" format:@"No handler for message from JS: %@", message];
}

handler(message[@"data"], responseCallback);
}
}
}

- (NSString *)_serializeMessage:(id)message {
return [[NSString alloc] initWithData:[NSJSONSerialization dataWithJSONObject:message options:0 error:nil] encoding:NSUTF8StringEncoding];
}

- (NSArray*)_deserializeMessageJSON:(NSString *)messageJSON {
return [NSJSONSerialization JSONObjectWithData:[messageJSON dataUsingEncoding:NSUTF8StringEncoding] options:NSJSONReadingAllowFragments error:nil];
}

- (void)_log:(NSString *)action json:(id)json {
if (!logging) { return; }
if (![json isKindOfClass:[NSString class]]) {
json = [self _serializeMessage:json];
}
if ([json length] > 500) {
NSLog(@"WVJB %@: %@ [...]", action, [json substringToIndex:500]);
} else {
NSLog(@"WVJB %@: %@", action, json);
}
- (NSString*) _evaluateJavascript:(NSString*)javascriptCommand
{
return [_webView stringByEvaluatingJavaScriptFromString:javascriptCommand];
}



/* Platform specific internals: OSX
**********************************/
#if defined WVJB_PLATFORM_OSX
Expand Down Expand Up @@ -325,12 +185,9 @@ - (NSURLRequest *)webView:(WebView *)webView resource:(id)identifier willSendReq
#elif defined WVJB_PLATFORM_IOS

- (void) _platformSpecificSetup:(WVJB_WEBVIEW_TYPE*)webView webViewDelegate:(id<UIWebViewDelegate>)webViewDelegate handler:(WVJBHandler)messageHandler resourceBundle:(NSBundle*)bundle{
_messageHandler = messageHandler;
_webView = webView;
_webViewDelegate = webViewDelegate;
_messageHandlers = [NSMutableDictionary dictionary];
_webView.delegate = self;
_resourceBundle = bundle;
_base = [[WebViewJavascriptBridgeBase alloc] initWithWebViewType:@"WebView" handler:(WVJBHandler)messageHandler resourceBundle:(NSBundle*)bundle];
}

- (void) _platformSpecificDealloc {
Expand All @@ -342,19 +199,10 @@ - (void)webViewDidFinishLoad:(UIWebView *)webView {

_numRequestsLoading--;

if (_numRequestsLoading == 0 && ![[webView stringByEvaluatingJavaScriptFromString:@"typeof WebViewJavascriptBridge == 'object'"] isEqualToString:@"true"]) {
NSBundle *bundle = _resourceBundle ? _resourceBundle : [NSBundle mainBundle];
NSString *filePath = [bundle pathForResource:@"WebViewJavascriptBridge.js" ofType:@"txt"];
NSString *js = [NSString stringWithContentsOfFile:filePath encoding:NSUTF8StringEncoding error:nil];
[webView stringByEvaluatingJavaScriptFromString:js];
}

if (_startupMessageQueue) {
for (id queuedMessage in _startupMessageQueue) {
[self _dispatchMessage:queuedMessage];
}
_startupMessageQueue = nil;
if (_numRequestsLoading == 0 && ![[webView stringByEvaluatingJavaScriptFromString:[_base webViewJavascriptCheckCommand]] isEqualToString:@"true"]) {
[_base injectJavascriptFile:YES];
}
[_base dispatchStartUpMessageQueue];

__strong WVJB_WEBVIEW_DELEGATE_TYPE* strongDelegate = _webViewDelegate;
if (strongDelegate && [strongDelegate respondsToSelector:@selector(webViewDidFinishLoad:)]) {
Expand All @@ -377,11 +225,12 @@ - (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)
if (webView != _webView) { return YES; }
NSURL *url = [request URL];
__strong WVJB_WEBVIEW_DELEGATE_TYPE* strongDelegate = _webViewDelegate;
if ([[url scheme] isEqualToString:kCustomProtocolScheme]) {
if ([[url host] isEqualToString:kQueueHasMessage]) {
[self _flushMessageQueue];
if ([_base correctProcotocolScheme:url]) {
if ([_base correctHost:url]) {
NSString *messageQueueString = [self _evaluateJavascript:[_base webViewJavascriptFetchQueyCommand]];
[_base _flushMessageQueue:messageQueueString];
} else {
NSLog(@"WebViewJavascriptBridge: WARNING: Received unknown WebViewJavascriptBridge command %@://%@", kCustomProtocolScheme, [url path]);
[_base logUnkownMessage:url];
}
return NO;
} else if (strongDelegate && [strongDelegate respondsToSelector:@selector(webView:shouldStartLoadWithRequest:navigationType:)]) {
Expand Down
3 changes: 2 additions & 1 deletion WebViewJavascriptBridge/WebViewJavascriptBridgeBase.h
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ typedef NSDictionary WVJBMessage;

// setup delegate
@protocol WebViewJavascriptBridgeBaseDelegate <NSObject>
- (void) _evaluateJavascript:(NSString*)javascriptCommand;
- (NSString*) _evaluateJavascript:(NSString*)javascriptCommand;
@end


Expand Down Expand Up @@ -48,6 +48,7 @@ typedef NSDictionary WVJBMessage;
-(void) logUnkownMessage:(NSURL*)url;
-(NSString *) webViewJavascriptCheckCommand;
-(NSString *) webViewJavascriptFetchQueyCommand;
- (void) dispatchStartUpMessageQueue;


// probably dont need to be public
Expand Down
18 changes: 11 additions & 7 deletions WebViewJavascriptBridge/WebViewJavascriptBridgeBase.m
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@ -(id)initWithWebViewType:(NSString*)webViewType handler:(WVJBHandler)messageHand
_resourceBundle = bundle;
self.messageHandler = messageHandler;
self.messageHandlers = [NSMutableDictionary dictionary];
_uniqueId = 0;
return(self);
}

Expand Down Expand Up @@ -177,17 +178,20 @@ - (void)injectJavascriptFile:(BOOL)shouldInject {
NSString *filePath = [bundle pathForResource:@"WebViewJavascriptBridge.js" ofType:@"txt"];
NSString *js = [NSString stringWithContentsOfFile:filePath encoding:NSUTF8StringEncoding error:nil];
[self _evaluateJavascript:js];

if (_startupMessageQueue) {
for (id queuedMessage in _startupMessageQueue) {
[self _dispatchMessage:queuedMessage];
}
_startupMessageQueue = nil;
}
[self dispatchStartUpMessageQueue];
}

}

- (void) dispatchStartUpMessageQueue {
if (_startupMessageQueue) {
for (id queuedMessage in _startupMessageQueue) {
[self _dispatchMessage:queuedMessage];
}
_startupMessageQueue = nil;
}
}

-(BOOL)correctProcotocolScheme:(NSURL*)url {
if([[url scheme] isEqualToString:kCustomProtocolScheme]){
return YES;
Expand Down

0 comments on commit 589dc2a

Please sign in to comment.