iOS APP与H5交互的三种方法

一.- (BOOL)webView:(UIWebView)webView shouldStartLoadWithRequest:(NSURLRequest)request navigationType:(UIWebViewNavigationType)navigationType

这种方法是利用拦截webView响应的url,对url进行处理,同时把需要执行的方法名和参数都放入url中,实现app和H5之前的方法交互:

//遵守UIWebViewDelegate代理协议。
-(BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType{
    //拿到网页的实时url
    NSString *requestStr = [[request.URL absoluteString] stringByRemovingPercentEncoding];

// NSString* requestStr = @"H5GetAPPMethod://test?data={\"name\":\"wangyujian\",\"sex\":\"男\",\"age\":\"18\"}";

    //在url中寻找自定义协议头"H5GetAPPMethod://"
    if ([requestStr hasPrefix:@"H5GetAPPMethod://"]) {

        NSArray* arr1 = [url componentsSeparatedByString:@"://"];
    
    if (arr1.count >= 2) {
        
        NSArray* arr2 = [arr1[1] componentsSeparatedByString:@"?"];
        
        if (arr2.count >= 2) {
            
            NSString* method = arr2[0];
            
            NSString* jsonStr = [arr2[1] substringFromIndex:@"data=".length];
            NSData *JSONData = [jsonStr dataUsingEncoding:NSUTF8StringEncoding];

            NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:JSONData options:NSJSONReadingMutableLeaves error:nil];

                
            NSLog(@"method = %@,xxx = %@,dic = %@",method,jsonStr,dic);
            
//  方法名和参数解析
            [self runMethodWithName:method param:dic];
        }
        
    }

        return NO;
    }

    return YES;
}

//  方法名和参数解析&&运行方法
- (void)runMethodWithName:(NSString*)methodName param:(NSDictionary*)param{
    
    SEL selector = NSSelectorFromString(methodName);
    self.param = param;
    
//    // 这里报警告:PerformSelector may cause a leak because its selector is unknown
//    if ([self respondsToSelector:selector]) {
//        [self performSelector:selector];
//    }
    
    if ([self respondsToSelector:selector]){

        IMP imp = [self methodForSelector:selector];
         void (*func)(id, SEL) = (void *)imp;
         func(self, selector);
        
    }
    
}

- (void)test{
    NSLog(@"xxxxxxxx");
}


二. WKUserContentController

这个属性是WKWebView才有的属性,主要是通过WKScriptMessageHandler的代理方法- (void)userContentController:(WKUserContentController *)userContentController didReceiveScriptMessage:(WKScriptMessage *)message 进行交互。

- (void)creatWebView{
    WKWebViewConfiguration *configuration = [[WKWebViewConfiguration alloc] init]
    WKUserContentController *userContentController =[[WKUserContentController alloc]init];
    configuration.userContentController = userContentController;
    // 根据需要去设置对应的属性
    WKWebView *webView = [[WKWebView alloc]initWithFrame:self.view.bounds configuration:configuration];
    webView.navigationDelegate = self;
    [self.view addSubview:webView]; 
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:@"URL地址"]];
    [self.webView loadRequest:request];
    
    [userContentController addScriptMessageHandler:delegateController name:@"goBack"];
}

//WKScriptMessageHandler代理方法
- (void)userContentController:(WKUserContentController *)userContentController didReceiveScriptMessage:(WKScriptMessage *)message {
    if ([message.name isEqualToString:@"goBack"]) {
       // 如果监控到前端调用了 'goBack' 方法代码就会走进来,在这里做处理就行了
    }
}

注意:

- (void)addScriptMessageHandler:(id )scriptMessageHandler name:(NSString *)name;

- (void)removeScriptMessageHandlerForName:(NSString *)name;

这两个方法是成对出现的,每次调用了add就必须调用remove。

三. 第三方WebViewJavascriptBridge

1.建立 WebViewJavaScriptBridge 和 WebView 之间的关系。

_jsBridge = [WebViewJavascriptBridge bridgeForWebView:_webView];

2.方法调用

1)oc调js方法(通过data可以传值,通过 response可以接受js那边的返回值 )

id data = @{@"greetingFromObjC": @"Hi there, JS!" };
    [_bridgecallHandler:@"testJavascriptHandler" data:data responseCallback:^(idresponse) {
        NSLog(@"testJavascriptHandlerresponded: %@", response);
    }];

2)js调oc方法(可以通过data给oc方法传值,使用responseCallback将值再返回给js)

[_bridgeregisterHandler:@"testObjcCallback" handler:^(id data,WVJBResponseCallback responseCallback) {
        NSLog(@"testObjcCallback called:%@", data);
        responseCallback(@"Response fromtestObjcCallback");
    }];

最后:iOS调用H5方法
UIWebView:NSString *result = [webView stringByEvaluatingJavaScriptFromString:@"javascript:add(3,5);"];

WKWebView: [self.webView evaluateJavaScript:@"show()" completionHandler:^(id _Nullable response, NSError * _Nullable error) { //TODO }];

你可能感兴趣的:(iOS APP与H5交互的三种方法)