使用 PonyRouter 让 WebView 与 iOS 应用好好沟通

有无数种方法,可以让webView发送一个请求到原生应用,以下是一些通用的方法:

  • 使用 WebViewJavascriptBridge 库
  • 监听 webView:shouldStartLoadWithRequest:navigationType: 方法的调用

WebViewJavascriptBridge 存在某些内存泄漏问题,同时,该库依赖 UIWebViewDelegate,在使用上有各种不便。

与WebViewJavascriptBridge不同,PonyRouter 库并不使用 UIWebViewDelegate 方案, PonyRouter 使用 NSURLProtocol 方案拦截请求,并且可以为请求返回数据。

以下是使用 PonyRouter 截获请求的例子:

  1. 使用 PonyRouter 库,你需要为 WebView 定义一些URL规则
    例如 wechat://sayhello/ 或者 wechat://sayhello/?who=Pony
  2. 然后,在原生应用中,为这些URL定义他们的执行代码块
PGRNode *node = [[PGRNode alloc] init];
    node.scheme = @"wechat";
    node.identifier = @"sayhello";
    [node setExecutingBlock:^(NSURL *sourceURL, NSDictionary *params, NSObject *sourceObject) {
        NSLog(@"Oops, some one say hello to me.");
        if (params[@"who"] != nil) {
            NSLog(@"It's %@", params[@"who"]);
        }
    }];
    [[PGRApplication sharedInstance] addNode:node];
  1. 最后,在 WebView 中发送请求,一个简单的请求是直接使用 loadRequest
[self.webView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:@"wechat://sayhello/?who=Pony"]]];
  1. Run, 控制台就会输出
2015-11-19 13:13:53.380 PonyRouter[61135:965270] Oops, some one say hello to me.
2015-11-19 13:13:53.381 PonyRouter[61135:965270] It's Pony
  1. 自定义返回内容,让WebView显示执行结果
    PGRNode *node = [[PGRNode alloc] init];
    node.scheme = @"wechat";
    node.identifier = @"sayhello";
    [node setExecutingBlock:^(NSURL *sourceURL, NSDictionary *params, NSObject *sourceObject) {
        NSLog(@"Oops, some one say hello to me.");
        if (params[@"who"] != nil) {
            NSLog(@"It's %@", params[@"who"]);
        }
    }];
    [node setReturnableBlock:^id(NSURL *sourceURL, NSDictionary *params, NSObject *sourceObject) {
        return @"I known you called me!";
    }];
    [[PGRApplication sharedInstance] addNode:node];

PonyRouter 不仅限于 UIWebView.loadRequest() 方法,包括 AJAX、jQuery、a标签、iframe、AFNetworking 这些库都是可以完美支持的。

PonyRouter 相当于在你的应用中搭建了一个服务器!

你可能感兴趣的:(使用 PonyRouter 让 WebView 与 iOS 应用好好沟通)