ios-webview-call-nativeCode-or-native-call-jsCode

UIWebView中 通过js去调用客户端的代码,客户端回调js代码。
最近因为项目中有一些页面使用H5实现(不得不说给客户端减少了不小压力啊😂😂),但是有webview与客户端的交互,在使用过程当中遇到的问题做了一些总结。

我们模拟两个场景
在webview中点击某一个用户的头像通过客户端NativeCode实现进入该用户的资料页
网页代码

1
2
3
4
5
6
7
8
9
<a href = "tataufo://userprofile">
<img src="avatarurl"></img>
<a>

<script>
function reloadKey(key){
//reload html
}
</script>

1.当用户点击头像的时候,会发送请求 tataufo://userprofile 这是跟客户端之前约定好的一个格式,不需要回调
tataufo 是个AppScheme,userprofile你可以认为你提供给网页的接口,当然你可以传递参数
格式如下:tataufo://userprofile#{‘userid’:3}(这里使用的是json形式的参数)

2.当webview需要调用Native的share,会发送请求 tataufo://share#{‘callback’:’reloadKey’} ,客户端处理完之后会回调reloadKey这个函数

实现如下:

我们可以在WebView的代理

1
-(BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType

拦截到所有的请求,并且可以控制要不要继续加载

-(BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType
{
  NSURL *url=[request URL];
  if (url) {

      return NO;
    }else{
          NSString *myAppScheme = @"tataufo";
          if (![request.URL.scheme isEqualToString:myAppScheme]) {
              return YES;
          }
          NSArray *turnTypes = @[@"profile",@"share"]
          NSString *actionType = request.URL.host;
          if ([turnTypes containsObject:actionType]) {
              NSString *jsonDictString = [self decodeString:request.URL.fragment];
              [request.URL.fragment stringByReplacingPercentEscapesUsingEncoding:NSASCIIStringEncoding];
              DDLogDebug(jsonDictString);
              NSDictionary *resultDic = [jsonDictString objectFromJSONString];
              [self processTurnType:actionType params:resultDic];
              return NO;
          }
        }
  }
  return YES;
}

-(NSString *)decodeString:(NSString*)encodedString
{
    //NSString *decodedString = [encodedString stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding ];

    NSString *decodedString  = (NSString *)CFURLCreateStringByReplacingPercentEscapesUsingEncoding(NULL,
                                                                                                                     (__bridge CFStringRef)encodedString,
                                                                                                                     CFSTR(""),
                                                                                                                     CFStringConvertNSStringEncodingToEncoding(NSUTF8StringEncoding));
    return decodedString;
}


// 目前已有的类型actionType
- (void) processTurnType:(NSString *) type params:(NSDictionary *) dict
{
    if ([type isEqualToString:@"profile"]){
        if (dict.count == 0) {
            return;
        }
        NSInteger userid = [[dict objectForKey:@"userid"]integerValue];
        TUPersonalCenterSelfViewController *personCenter = [[TUPersonalCenterSelfViewController alloc] init];
        personCenter.userid = userid;
        [self.navigationController pushViewController:personCenter animated:YES];
    }else if ([type isEqualToString:@"share"]){
        if (dict.count == 0) {
            return;
        }
        NSString *callback = [dict objectForKey:@"callback"];
        [[TUNetworkManager sharedInstance] shareSuccess:^(NSMutableDictionary *dict) {
            NSString *key = [dict objectForKey:@"key"];
            NSString *jsFunction = [NSString stringWithFormat:@"%@('%@')",callback,key];
            //执行网页已经存在的js函数
            [yourWebview stringByEvaluatingJavaScriptFromString:jsFunction];
        } failure:^(NSError *error) {

        }];
    }
}

希望可帮到你,Best wishes