DJSRouter(JS Call OC)考え方とコアコード
4175 ワード
WebViewとJavaScriptは相互作用します. DLJavascriptRouter->現在のWebインターフェースJSを引き出してWebViewプロキシ方法でこの方法を呼び出します. ジャンプ情報を取得する は、Requestのscheme、path、queryを取得し、schemeが対応するかどうかを判定し、pathはJS構成の格納場所gapDictの が存在するかどうかを判定する.は、queryを処理し、NSInvocationによって方法を実行し、複数のパラメータ に入ることができる.方法の実行結果を取得し、もしあれば、JS に戻ります.
copyRight@DylanWild2015-1-30
/*!
* @brief WebView JS
*/
- (void)webViewDidFinishLoad;
gapDictは設定情報を保存するために使用されます.path:メソッド名#define DLJavascriptGetMapMethodName @"getMethodMap();"
- (void)webViewDidFinishLoad {
// JS
NSString * result = [_webView stringByEvaluatingJavaScriptFromString:DLJavascriptGetMapMethodName];
[self.gapDict setValuesForKeysWithDictionary:[self toDict:result]];
}
- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType {
return [_router handleWebViewForwardAction:request];
}
/*!
* @brief WebView , Gap
*/
- (BOOL)handleWebViewForwardAction: (NSURLRequest *)request;
/*!
* @brief WebView , Gap
*/
- (BOOL)handleWebViewForwardAction: (NSURLRequest *)request {
if (!self.scheme) {
return YES;
}
NSURL * url = request.URL;
NSString * scheme = url.scheme;
if ([self.scheme isEqualToString:scheme]) {
//
NSString * path = url.path;
NSString * query = url.query;
//
if ([self.gapDict.allKeys containsObject:path]) {
//
id result = [self operatedPathAndQuery:path query:query];
if (result) {
//
[self callBack:result path:path];
}
return NO;
} else {
return YES;
}
}
return YES;
}
- (id)operatedPathAndQuery: (NSString *)path query: (NSString *)query {
// key = value & key = value
NSArray * queryArray = [query componentsSeparatedByString:@"&"];
NSArray * array = [NSMutableDictionary dictionary];
for (NSString * separateString in queryArray) {
NSArray * tempArray = [separateString componentsSeparatedByString:@"="];
if (tempArray.count == 2) {
NSString * value = tempArray[1];
[array addObject:value];
}
}
if (array.count != 0) {
// can operated
NSString * methodName = [self.gapDict valueForKey:path];
SEL selector = NSSelectorFromString:methodName];
// Get method count
NSInteger methodParamCount = [methodName componentsSeparatedByString:@":"].count;
NSMethodSignature *signature = [self.handler methodSignatureForSelector:selector];
if (signature) {
NSInvocation* invocation = [NSInvocation invocationWithMethodSignature:sig];
[invocation setTarget:self.handler];
[invocation setSelector:selector];
// Set param
for (int i = 1; i < methodParamCount + 1; i ++) {
id object = array[i];
[invocation setArgument:&object atIndex:i + 1];
}
[invocation invoke];
if (signature.methodReturnLength) {
id resultObject;
[invocation getReturnValue:&resultObject];
return resultObject;
} else {
return nil;
}
} else {
return nil;
}
}
}
- (void)callBack: (id)result path: (NSString *)path {
[self.webView stringByEvaluatingJavaScriptFromString:@"dl_callBack('%@', '%@');", path, result];
}
copyRight@DylanWild2015-1-30