服务器之家:专注于服务器技术及软件下载分享
分类导航

PHP教程|ASP.NET教程|Java教程|ASP教程|编程技术|正则表达式|C/C++|IOS|C#|Swift|Android|VB|R语言|JavaScript|易语言|vb.net|

服务器之家 - 编程语言 - IOS - IOS中UIWebView、WKWebView之JS交互

IOS中UIWebView、WKWebView之JS交互

2021-03-18 15:40小小棒棒糖 IOS

本篇文章主要介绍了IOS中UIWebView、WKWebView之JS交互,小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编过来看看吧

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

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

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

旧方式

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

iOS端:

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

JS端:

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

UIWebView+JSExport方式

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

使用方式

OC调JS:

?
1
[_webView InterActionToJs:@"alertMobile('15625298071')"];

JS调OC:

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

添加动作

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

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

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

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

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

WKWebView+WKScriptMessageHandler方式

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

使用方式

OC调JS:

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

JS调OC:

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

添加动作

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

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

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

其中callBack是通过WKScriptMessageHandler实现的

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

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

原文链接:http://www.jianshu.com/p/5b2bbd283e2f?utm_source=tuicool&utm_medium=referral

延伸 · 阅读

精彩推荐
  • IOS关于iOS自适应cell行高的那些事儿

    关于iOS自适应cell行高的那些事儿

    这篇文章主要给大家介绍了关于iOS自适应cell行高的那些事儿,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的...

    daisy6092021-05-17
  • IOSiOS中tableview 两级cell的展开与收回的示例代码

    iOS中tableview 两级cell的展开与收回的示例代码

    本篇文章主要介绍了iOS中tableview 两级cell的展开与收回的示例代码,小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编过来看看吧...

    J_Kang3862021-04-22
  • IOS解析iOS开发中的FirstResponder第一响应对象

    解析iOS开发中的FirstResponder第一响应对象

    这篇文章主要介绍了解析iOS开发中的FirstResponder第一响应对象,包括View的FirstResponder的释放问题,需要的朋友可以参考下...

    一片枫叶4662020-12-25
  • IOSiOS布局渲染之UIView方法的调用时机详解

    iOS布局渲染之UIView方法的调用时机详解

    在你刚开始开发 iOS 应用时,最难避免或者是调试的就是和布局相关的问题,下面这篇文章主要给大家介绍了关于iOS布局渲染之UIView方法调用时机的相关资料...

    windtersharp7642021-05-04
  • IOSIOS开发之字典转字符串的实例详解

    IOS开发之字典转字符串的实例详解

    这篇文章主要介绍了IOS开发之字典转字符串的实例详解的相关资料,希望通过本文能帮助到大家,让大家掌握这样的方法,需要的朋友可以参考下...

    苦练内功5832021-04-01
  • IOSiOS通过逆向理解Block的内存模型

    iOS通过逆向理解Block的内存模型

    自从对 iOS 的逆向初窥门径后,我也经常通过它来分析一些比较大的应用,参考一下这些应用中某些功能的实现。这个探索的过程乐趣多多,不仅能满足自...

    Swiftyper12832021-03-03
  • IOSiOS 雷达效果实例详解

    iOS 雷达效果实例详解

    这篇文章主要介绍了iOS 雷达效果实例详解的相关资料,需要的朋友可以参考下...

    SimpleWorld11022021-01-28
  • IOSIOS 屏幕适配方案实现缩放window的示例代码

    IOS 屏幕适配方案实现缩放window的示例代码

    这篇文章主要介绍了IOS 屏幕适配方案实现缩放window的示例代码,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要...

    xiari5772021-06-01