IOS中UIWebView、WKWebView之JS交互

所属分类: 软件编程 / IOS 阅读数: 1005
收藏 0 赞 0 分享

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

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

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

旧方式

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

iOS端:

- (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端:

<!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:

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

JS调OC:

- (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;
    }
  }];
}

添加动作

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

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

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

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

@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:

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

JS调OC:

//注册交互类型
  [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;
    }
  }];

添加动作

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

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

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

其中callBack是通过WKScriptMessageHandler实现的

- (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);
    }
  });
}

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

更多精彩内容其他人还在看

iOS开发笔记--详解UILabel的相关属性设置

这篇文章主要介绍了iOS开发笔记--详解UILabel的相关属性设置,对初学者具有一定的参考价值,有需要的可以了解一下。
收藏 0 赞 0 分享

iOS中获取系统相册中的图片实例

这篇文章主要介绍了iOS中获取系统相册中的图片实例,具有一定的参考价值没有需要的朋友可以了解一下。
收藏 0 赞 0 分享

iOS 检测网络状态的两种方法

一般有Reachability和AFNetworking监测两种方式,都是第三方的框架,下文逐一详细给大家讲解,感兴趣的朋友一起看看吧
收藏 0 赞 0 分享

IOS 性能优化中离屏渲染

本文主要介绍了IOS 性能优化中离屏渲染的资料,提供了几种方法讲解了优化,有需要的小伙伴可以参考下
收藏 0 赞 0 分享

iOS获取当前设备型号等信息(全)包含iPhone7和iPhone7P

这篇文章主要介绍了iOS获取当前设备型号设备信息的总结包含iPhone7和iPhone7P,包括ios7之前之后的获取方式,本文接的非常详细,具有参考借鉴价值,需要的朋友可以参考下
收藏 0 赞 0 分享

iOS实现爆炸的粒子效果示例代码

之前在网上看到了一个Android实现的爆炸效果,感觉非常不错,所以自己尝试用iOS来实现下效果,现在将实现的过程、原理以及遇到的问题分享给大家,有需要的朋友们可以参考借鉴,下面来一起看看吧。
收藏 0 赞 0 分享

iOS毕业设计之天气预报App

这篇文章主要为大家详细介绍了iOS毕业设计之天气预报App,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
收藏 0 赞 0 分享

iOS轻点、触摸和手势代码开发

这篇文章主要为大家详细介绍了iOS轻点、触摸和手势代码开发,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
收藏 0 赞 0 分享

iOS 实现多代理的方法及实例代码

这篇文章主要介绍了iOS 实现多代理的方法及实例代码的相关资料,需要的朋友可以参考下
收藏 0 赞 0 分享

iOS文字渐变色效果的实现方法

在大家日常开发iOS的过程中,可能会遇到要实现文字渐变色的效果,这篇文章文章通过示例代码和详细的步骤介绍了如何利用iOS实现文字渐变色的效果,实现后的很不错,感兴趣的朋友们下面来一起看看吧。
收藏 0 赞 0 分享
查看更多