Skip to content

Commit

Permalink
init
Browse files Browse the repository at this point in the history
  • Loading branch information
hikui committed Apr 9, 2014
0 parents commit 2cc5eed
Show file tree
Hide file tree
Showing 17 changed files with 959 additions and 0 deletions.
30 changes: 30 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
# Created by http://www.gitignore.io

### Xcode ###
build/
*.pbxuser
!default.pbxuser
*.mode1v3
!default.mode1v3
*.mode2v3
!default.mode2v3
*.perspectivev3
!default.perspectivev3
xcuserdata
*.xccheckout
profile
*.moved-aside
DerivedData
*.hmap
*.ipa



### Objective-C ###
# CocoaPods
#
# We recommend against adding the Pods directory to your .gitignore. However
# you should judge for yourself, the pros and cons are mentioned at:
# http://guides.cocoapods.org/using/using-cocoapods.html#should-i-ignore-the-pods-directory-in-source-control?
#
# Pods/
465 changes: 465 additions & 0 deletions MHGJavascriptCore.xcodeproj/project.pbxproj

Large diffs are not rendered by default.

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

23 changes: 23 additions & 0 deletions MHGJavascriptCore/Images.xcassets/AppIcon.appiconset/Contents.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
{
"images" : [
{
"idiom" : "iphone",
"size" : "29x29",
"scale" : "2x"
},
{
"idiom" : "iphone",
"size" : "40x40",
"scale" : "2x"
},
{
"idiom" : "iphone",
"size" : "60x60",
"scale" : "2x"
}
],
"info" : {
"version" : 1,
"author" : "xcode"
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
{
"images" : [
{
"orientation" : "portrait",
"idiom" : "iphone",
"extent" : "full-screen",
"minimum-system-version" : "7.0",
"scale" : "2x"
},
{
"orientation" : "portrait",
"idiom" : "iphone",
"subtype" : "retina4",
"extent" : "full-screen",
"minimum-system-version" : "7.0",
"scale" : "2x"
}
],
"info" : {
"version" : 1,
"author" : "xcode"
}
}
15 changes: 15 additions & 0 deletions MHGJavascriptCore/MHGAppDelegate.h
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
//
// MHGAppDelegate.h
// MHGJavascriptCore
//
// Created by 缪和光 on 9/04/2014.
// Copyright (c) 2014 Hokuang. All rights reserved.
//

#import <UIKit/UIKit.h>

@interface MHGAppDelegate : UIResponder <UIApplicationDelegate>

@property (strong, nonatomic) UIWindow *window;

@end
64 changes: 64 additions & 0 deletions MHGJavascriptCore/MHGAppDelegate.m
Original file line number Diff line number Diff line change
@@ -0,0 +1,64 @@
//
// MHGAppDelegate.m
// MHGJavascriptCore
//
// Created by 缪和光 on 9/04/2014.
// Copyright (c) 2014 Hokuang. All rights reserved.
//

#import "MHGAppDelegate.h"
#import "MHGJavascriptBridge.h"

@implementation MHGAppDelegate

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];

MHGJavascriptBridge *bridge = [[MHGJavascriptBridge alloc]init];

MHGNativeCodeBlock b = ^(NSArray *params){
NSLog(@"%@",params);
};

bridge.nativeBlocks[@"hahaha"] = [b copy];

NSURL *url = [NSURL URLWithString:@"mhgjavascriptbridge://mhgjavascriptbridge.herkuang.info/call_native_block/hahaha/?params=%5B1%2C2%2C3%2C4%2C5%2C%7B%22aaa%22%3A%22dddd%22%7D%5D"];
NSURLRequest *req = [[NSURLRequest alloc]initWithURL:url];

[bridge interceptRequest:req];

// Override point for customization after application launch.
self.window.backgroundColor = [UIColor whiteColor];
[self.window makeKeyAndVisible];
return YES;
}

- (void)applicationWillResignActive:(UIApplication *)application
{
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}

- (void)applicationDidEnterBackground:(UIApplication *)application
{
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}

- (void)applicationWillEnterForeground:(UIApplication *)application
{
// Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}

- (void)applicationDidBecomeActive:(UIApplication *)application
{
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}

- (void)applicationWillTerminate:(UIApplication *)application
{
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}

@end
23 changes: 23 additions & 0 deletions MHGJavascriptCore/MHGJavascriptBridge.h
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
//
// MHGJavascirptCore.h
// MHGJavascriptCore
//
// Created by 缪和光 on 9/04/2014.
// Copyright (c) 2014 Hokuang. All rights reserved.
//

#import <Foundation/Foundation.h>

typedef void(^MHGNativeCodeBlock)(NSArray *);

@interface MHGJavascriptBridge : NSObject<UIWebViewDelegate>

@property (nonatomic, unsafe_unretained) UIWebView *webView;

@property (nonatomic, strong) NSMutableDictionary *nativeBlocks;

- (BOOL)interceptRequest:(NSURLRequest *)request;

- (NSString *)callJavascriptFunction:(NSString *)functionName withParams:(NSArray *)params;

@end
24 changes: 24 additions & 0 deletions MHGJavascriptCore/MHGJavascriptBridge.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
var MHGJavascriptBridge = (function(){
var scheme = "mhgjavascriptbridge";
var host = "mhgjavascriptbridge.herkuang.info";
var action = "call_native_block";
var makeURL = function(funcName, arguments) {
var URL = scheme+"://"+host+"/"+action+"/"+funcName+"/";
var argsArray = Array.prototype.slice.call(arguments);
var argsString = encodeURIComponent(JSON.stringify(argsArray));
URL += "?params="+argsString;
return URL;
};

return {
callNativeBlock: function(funcName, arguments) {
return makeURL(funcName, arguments);
}
};

})();


var test = MHGJavascriptBridge.callNativeBlock("hahaha",[1,2,3,4,5,{"aaa":"dddd"}]);

console.log(test);
153 changes: 153 additions & 0 deletions MHGJavascriptCore/MHGJavascriptBridge.m
Original file line number Diff line number Diff line change
@@ -0,0 +1,153 @@
//
// MHGJavascirptCore.m
// MHGJavascriptCore
//
// Created by 缪和光 on 9/04/2014.
// Copyright (c) 2014 Hokuang. All rights reserved.
//

#import "MHGJavascriptBridge.h"

@interface MHGJavascripBridgeUtility : NSObject

+ (NSDictionary *)dictionaryWithURLArgumentsString:(NSString *)args;
+ (NSString *)URLArgumentsStringFromDictionary:(NSDictionary *)dict;

+ (NSString *)stringByURLEncoding:(NSString *)str;
+ (NSString *)stringByURLDecoding:(NSString *)str;

@end

@implementation MHGJavascripBridgeUtility

+ (NSDictionary *)dictionaryWithURLArgumentsString:(NSString *)args
{
NSMutableDictionary *ret = [NSMutableDictionary dictionary];
NSArray *components = [args componentsSeparatedByString:@"&"];
[components enumerateObjectsUsingBlock:^(NSString *component, NSUInteger idx, BOOL *stop) {
if (component.length == 0) {
return;
}
NSRange pos = [component rangeOfString:@"="];
NSString *key;
NSString *val;
if (pos.location == NSNotFound) {
key = [self stringByURLDecoding:component];
val = @"";
} else {
key = [self stringByURLDecoding:[component substringToIndex:pos.location]];
val = [self stringByURLDecoding:[component substringFromIndex:pos.location + pos.length]];
if (!key) key = @"";
if (!val) val = @"";
[ret setObject:val forKey:key];
}
}];
return ret;
}

+ (NSString *)URLArgumentsStringFromDictionary:(NSDictionary *)dict
{
__block NSMutableArray *arguments = [NSMutableArray arrayWithCapacity:dict.count];
[dict enumerateKeysAndObjectsUsingBlock:^(id key, id obj, BOOL *stop) {
NSString *encodedKey = [self stringByURLEncoding:key];
NSString *value = [dict objectForKey:key];
NSString *encodedValue = [self stringByURLEncoding:[value description]];
NSString *kvPair = [NSString stringWithFormat:@"%@=%@", encodedKey, encodedValue];
[arguments addObject:kvPair];
}];
return [arguments componentsJoinedByString:@"&"];
}

+ (NSString *)stringByURLEncoding:(NSString *)str
{
NSString *result = (NSString *)CFBridgingRelease(CFURLCreateStringByAddingPercentEscapes(NULL,(CFStringRef)str,NULL,
(CFStringRef)@";/?:@&=$+{}<>,",kCFStringEncodingUTF8));
return result;
}

+ (NSString *)stringByURLDecoding:(NSString *)str
{
NSMutableString *outputStr = [NSMutableString stringWithString:str];
[outputStr replaceOccurrencesOfString:@"+"
withString:@" "
options:NSLiteralSearch
range:NSMakeRange(0, [outputStr length])];

return [outputStr stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
}

@end

@implementation MHGJavascriptBridge

- (id)init
{
self = [super init];
if (self) {
_nativeBlocks = [[NSMutableDictionary alloc]init];
}
return self;
}

- (BOOL)interceptRequest:(NSURLRequest *)request
{
// 格式:mhgjavascriptbridge://call_native_block/blockName?params=[1,2,{"xx":"yy"},"mmm"]

static NSString *scheme = @"mhgjavascriptbridge";
NSURL *url = request.URL;
if (![url.scheme isEqualToString:scheme]) {
return NO;
}


NSArray *pathComponents = url.pathComponents;
if (![pathComponents[1] isEqualToString:@"call_native_block"]) {
return NO;
}

NSString *blockName = pathComponents[2];
MHGNativeCodeBlock block = self.nativeBlocks[blockName];
if (block == NULL) {
return NO;
}
NSString *queryString = [MHGJavascripBridgeUtility stringByURLDecoding:url.query];
queryString = [queryString substringFromIndex:7];

if (queryString) {
NSArray *nativeParams = [NSJSONSerialization JSONObjectWithData:[queryString dataUsingEncoding:NSUTF8StringEncoding] options:0 error:nil];
if (nativeParams == nil) {
return NO;
}
block(nativeParams);
}else{
block(nil);
}

return YES;
}

- (NSString *)callJavascriptFunction:(NSString *)functionName withParams:(NSArray *)params
{
NSMutableString *jsParamString = [[NSMutableString alloc]init];

__block BOOL shouldContinue = YES;
[params enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
NSData *JSONData = [NSJSONSerialization dataWithJSONObject:obj options:0 error:nil];
NSString *JSONString = [[NSString alloc]initWithData:JSONData encoding:NSUTF8StringEncoding];
if (JSONString == nil) {
*stop = YES;
shouldContinue = NO;
}
[jsParamString appendString:JSONString];
if (idx != params.count-1) {
[jsParamString appendString:@","];
}
}];
if (!shouldContinue) {
return nil;
}
NSString *call = [NSString stringWithFormat:@"%@(%@)",functionName,jsParamString];
return [self.webView stringByEvaluatingJavaScriptFromString:call];
}

@end
Loading

0 comments on commit 2cc5eed

Please sign in to comment.