查看: 623|回复: 0

[IOS开发教程] IOS中UIWebView、WKWebView之JS交互

发表于 2017-8-2 08:00:02

做客户端开发,肯定避免不了JS交互,于是自己对苹果接口做了个简易封装:

JSExport-->UIWebView+Interaction、WKScriptMessageHandler -->WKWebView+Interaction以备以后使用。

代码非常简洁,见这里:https://github.com/V5zhou/JSInteraction.git

旧方式

旧的交互方式有通过UIWebViewDelegate实现的:JS与客户端定义好跳转页面参数,在将要跳转时捕获关键字,然后处理业务。

iOS端:

  1. - (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType {
  2. NSString *urlString = [[request URL] absoluteString];
  3. if ([urlString isEqualToString:@"objc://loading"]) {
  4. if (_gotoRootViewController) {
  5. _gotoRootViewController();
  6. }
  7. }
  8. return YES;
  9. }
复制代码

JS端:

  1. <!DOCTYPE html>
  2. <html>
  3. <title>test</title>
  4. <meta charset="utf-8">
  5. <body>
  6. <a href="javascript:document.location = 'objc://loading'" rel="external nofollow" class="btn">这是交互按钮</a>
  7. </body>
  8. </html>
复制代码

UIWebView+JSExport方式

导入JavaScriptCore.framework,并导入我的扩展类#import "UIWebView+Interaction.h"。

使用方式

OC调JS:

  1. [_webView InterActionToJs:@"alertMobile('15625298071')"];
复制代码

JS调OC:

  1. - (void)webViewDidFinishLoad:(UIWebView *)webView {
  2. [self.webView InterActionToOc:^(InterActionOcType functionType, NSDictionary *param) {
  3. switch (functionType) {
  4. case InterActionOcType_alert:
  5. {
  6. UIAlertView *alert = [[UIAlertView alloc] initWithTitle:param[@"title"] message:param[@"content"] delegate:nil cancelButtonTitle:nil otherButtonTitles:@"确定", nil];
  7. [alert show];
  8. }
  9. break;
  10. case InterActionOcType_present:
  11. {
  12. self.modalTransitionStyle = UIModalTransitionStyleCrossDissolve;
  13. Class Cls = NSClassFromString(param[@"toController"]);
  14. BOOL isAnimate = [param[@"animate"] boolValue];
  15. UIViewController *ctl = [[Cls alloc] init];
  16. [self presentViewController:ctl animated:isAnimate completion:nil];
  17. }
  18. break;
  19. default:
  20. break;
  21. }
  22. }];
  23. }
复制代码

添加动作

  1. //自定义添加功能类型
  2. typedef NS_ENUM(NSUInteger, InterActionOcType) {
  3. InterActionOcType_alert = 0,
  4. InterActionOcType_present,
  5. InterActionOcType_xxxxxxx, //有啥需求就和这里添加
  6. };
复制代码

并且对应的html中添加JS,参数封装为字典形式。例:

  1. function myPresent(ctl) {
  2. var param = new Array();
  3. param["animate"] = 1;
  4. param["toController"] = "SecondViewController";
  5. WebViewInteraction.callBack(1, param);
  6. }
复制代码

其中callBack是通过这个JSExport实现的

  1. @protocol WebViewJSExport <JSExport>
  2. JSExportAs
  3. (callBack /** callBack 作为js方法的别名 */,
  4. - (void)awakeOC:(InterActionOcType)type param:(NSDictionary *)param
  5. );
  6. @end
复制代码

WKWebView+WKScriptMessageHandler方式

导入WebKit.framework,并导入我的扩展类#import "WKWebView+Interaction.h"。

使用方式

OC调JS:

  1. [self.wkWebView InterActionToJs:@"JSReloadTitle('你点了刷新JS按钮,我没猜错!')"];
复制代码

JS调OC:

  1. //注册交互类型
  2. [self.wkWebView registerScriptTypes:@{@"OCDismiss" : @(WKInterActionOcType_dismiss),
  3. @"OCShowAlert" : @(WKInterActionOcType_alert)}];
  4. [self.wkWebView InterActionToOc:^(WKInterActionOcType functionType, NSDictionary *param) {
  5. switch (functionType) {
  6. case WKInterActionOcType_dismiss:
  7. {
  8. BOOL isAnimate = [param[@"animate"] boolValue];
  9. [self dismissViewControllerAnimated:isAnimate completion:nil];
  10. }
  11. break;
  12. case WKInterActionOcType_alert:
  13. {
  14. UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"JS去做平方" message:nil delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确定", nil];
  15. alert.alertViewStyle = UIAlertViewStylePlainTextInput;
  16. [alert show];
  17. }
  18. break;
  19. default:
  20. break;
  21. }
  22. }];
复制代码

添加动作

  1. //自定义添加功能类型
  2. typedef NS_ENUM(NSUInteger, WKInterActionOcType) {
  3. WKInterActionOcType_alert = 0,
  4. WKInterActionOcType_dismiss,
  5. WKInterActionOcType_xxxxxxx, //有啥需求就和这里添加
  6. };
复制代码

并且对应的html中添加JS,参数封装为字典形式。例:

  1. //js调oc
  2. function myDismiss() {
  3. window.webkit.messageHandlers.OCDismiss.postMessage({"animate" : 1}); //这里的OCDismiss对应注册类型
  4. }
复制代码

其中callBack是通过WKScriptMessageHandler实现的

  1. - (void)userContentController:(WKUserContentController *)userContentController didReceiveScriptMessage:(WKScriptMessage *)message {
  2. dispatch_async(dispatch_get_main_queue(), ^{
  3. NSString *name = message.name;
  4. NSDictionary *value = message.body;
  5. WKInterActionOcType type = [self.typeDict[name] integerValue];
  6. if (self.block) {
  7. self.block(type, value);
  8. }
  9. });
  10. }
复制代码

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持程序员之家。



回复

使用道具 举报