Web与 OC交互总结

Web与 OC交互总结
1,原生方法,通过url传值
web代码:




iOS代码:

  • (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType{
    NSString *requestString = [[request URL] absoluteString];
    NSLog(@"拦截请求:%@",requestString);
    //requestString
    //前端把数据放到requestString中,通过;区分
    //有时候根据需要,对url string进行encode和decode
    NSArray *components = [requestString componentsSeparatedByString:@";"];
    //web:getperfectclick 这种协议定义,ios和android统一
    if([components count]>1 && ([[components objectAtIndex:0] isEqualToString:@"web:getperfectclick"]))
    {
    NSString *element = [components objectAtIndex:1];
    //element转成字典
    NSDictionary *elementsDic = [element JSONValue];
    NSLog(@"%@",elementsDic);
    //下面根据字典信息做相应动作
    //获取参数后调用OC客户端逻辑
    //将OC端获取数据返回给web即手动调用web代码,需要web定义方法,iOS调用
    }
    return YES;
    }
  • (void)setHtmlData:(NSDictionary *)aDic{
    //active.setContentback 这种协议定义,ios和android统一
    NSString *resultInfo = [NSString stringWithFormat: @"active.setContentback('%@')",[aDic JSONRepresentation]];
    [_webBrowser stringByEvaluatingJavaScriptFromString:resultInfo];
    }

优缺点解析
1,原理,规定协议,即url的url的字符串iOS和andriod统一,传参数一样,
2,目前了解到iOS和andriod实现互调在web端的代码不一致
3,web传参给OC通过url,OC传参数web通过调用web定义方法
4,在一套网页请求客户端携带参数,并在客户端获取数据后返回给web端,需要客户端通过url判断web端请求类型和请求参数, 并且web端定义方法,客户端在获取到数据后返回给网页

2,JavaScriptCore
web代码:


这是按钮调用




iOS代码:

  • (void)webViewDidFinishLoad:(UIWebView *)webView
    {
    JSContext *context = [self.webView valueForKeyPath:@"documentView.webView.mainFrame.javaScriptContext"];
    context[@"share"] = ^() {
    NSArray *args = [JSContext currentArguments];
    if (args.count < 3) {
    return ;
    }
    NSString *title = [args[0] toString];
    NSString *content = [args[1] toString];
    NSString *url = [args[2] toString];
    // 在这里执行分享的操作

      // 将分享结果返回给js
      NSString *jsStr = [NSString stringWithFormat:@"shareResult('%@','%@','%@')",title,content,url];
    

//这个位置将调用js方法,需web定义方法,将参数返回
[[JSContext currentContext] evaluateScript:jsStr];
};
}

优缺点解析
1,获取documentView.webView.mainFrame.javaScriptContext对象,定义OC方法给js调用, 同时在方法内部调用js定义方法将获得参数进行需求处理后获得数据返回
2,在一套网页请求客户端携带参数,并在客户端获取数据后返回给web端,需要客户端定义方法名称网页调用,并处理网页传的请求参数, 最后web端定义方法,客户端在获取到数据后返回给网页

3,WebViewJavascriptBridge框架
web代码:

aaa

iOS代码:

  • (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType {
    return ![self.webView dispatchURL:request.URL];
    }

  • (NSDictionary *)mytest:(NSDictionary *)params {

    NSLog(@"params:%@,%@",params[@"name"],params[@"val"]);
    return @{@"name2":@"你",@"val2":@"很棒"};
    }

  • (void)webViewDidFinishLoad:(UIWebView *)webView {
    // 让js方法和OC方法进行桥接
    [webView registerJSMethod:@"mytest" target:self method:@selector(mytest:)];
    }

//框架内部实现部分方法

pragma mark - 注册url进行调用OC和js -

  • (BOOL)dispatchURL:(NSURL *)url {
    if([url.scheme isEqualToString:kBridgeScheme]) {
    NSString *jsMethod = url.host;
    NSDictionary *invokeParams = [url.query params][@"params"];
    NSInvocation *invocation = [[self registeredMethods] objectForKey:jsMethod];
    [invocation setArgument:&invokeParams atIndex:2];
    __autoreleasing NSDictionary *result = nil;
    [invocation invoke];
    [invocation getReturnValue:&result];
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:result options:NSJSONWritingPrettyPrinted error:nil];
    if(jsonData) {
    NSString *jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
    NSString *js = [NSString stringWithFormat:@"CallbackCaches"%@"",jsMethod,[jsonString stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]]];
    [self stringByEvaluatingJavaScriptFromString:js];
    }
    [self stringByEvaluatingJavaScriptFromString:[NSString stringWithFormat:@"CallbackMap["%@"]=NULL;",jsMethod]];
    return YES;
    }
    return NO;
    }

pragma mark - 注册方法 -

  • (void)registerJSMethod:(NSString *)jsMethod target:(id)target method:(SEL)method {
    //缓存方法
    NSMethodSignature *signature = [[target class] instanceMethodSignatureForSelector:method];
    NSInvocation *invocation = [NSInvocation invocationWithMethodSignature:signature];

    invocation.target = target;
    invocation.selector = method;

    NSMutableDictionary *registeredMethods = self.registeredMethods;
    [registeredMethods setObject:invocation forKey:jsMethod];

    //设置回调函数缓存
    if(![self isJSVariable:@"CallbackCaches"]) {
    [self stringByEvaluatingJavaScriptFromString:@"var CallbackCaches = new Object();"];
    }

    //运行时植入js代码,使js拥有js回调能力
    if(![self isJSFunction:jsMethod]) {
    NSString *js = [NSString stringWithFormat:@"%@ = function(params,callback){CallbackCaches["%@"]=callback;window.location.href="%@://%@?params="+encodeURIComponent(JSON.stringify(params));}",jsMethod,jsMethod,kBridgeScheme,jsMethod];
    [self stringByEvaluatingJavaScriptFromString:js];
    }

}

你可能感兴趣的:(Web与 OC交互总结)