iOS WKWebView与web 交互

iOS 之 WKWebView 原生交互

中心思想:web页面得到iOS的值靠js注入;iOS得到web页面的值靠WKWebView的发送消息机制

JS注入 :告知web端传入的参数

WKUserContentController

应用:比如我们APP与网页需要传参,比如用户ID,用户需要打开web端的个人中心,那么进行一次注入,web端就知道了要打开谁的用户界面。也可以传递数值,flag等等等。

//我的宏定义
#define Js1 @"function %@() { return '%@';}; "

协议

@interface YKWebViewViewController ()<WKScriptMessageHandler>

我在其他地方进行的初始化

WKWebViewConfiguration *configuration = [[WKWebViewConfiguration alloc] init];
//    configuration.selectionGranularity = WKSelectionGranularityCharacter;
    WKWebView *webView          = [[WKWebView alloc]initWithFrame:self.view.bounds configuration:configuration];
    webView.navigationDelegate  = self;
    webView.UIDelegate          = self;
    self.webView                = webView;
    [self.view addSubview:self.webView];
//js注入
    NSString *Str = [NSString stringWithFormat:Js1,@"getJSessionId",@"123456"];

    //创建自定义JS 注意两个参数
    WKUserScript *noneSelectScript = [[WKUserScript alloc] initWithSource:Str  injectionTime:WKUserScriptInjectionTimeAtDocumentStart forMainFrameOnly:NO];

    // 将自定义JS加入到配置里
    [self.webView.configuration.userContentController addUserScript:noneSelectScript];

//添加对iOS键来监听来自web端的消息
    [self.webView.configuration.userContentController addScriptMessageHandler:self name:@"iOS"];

    //加载
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:self.url] cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:20];
    [self.webView loadRequest:request];

走到这里,js会在onload()后,创建Document前被注入在页面中,web端的程序猿就可以调用了,但要注意上面说的顺序。

iOS调用web端

NSString *evaluateJavaScript = [NSString stringWithFormat:@"h5GetImageUrl(%@)",tempString];
    NSLog(@"js:%@",evaluateJavaScript);

//执行一段JS
    [self.webView evaluateJavaScript:evaluateJavaScript completionHandler:^(id _Nullable object, NSError * _Nullable error) {
        if (error!=nil) {
            [MBProgressHUD showError:@"图片上传失败" toView:self.view];
        }
    }];

我这里向web端执行h5GetImageUrl来将我iOS端上传完成的图片URL交给web端进行渲染。当然h5GetImageUrl是前端写好的,也可以靠上面的注入,不过这个要看自己项目中的逻辑操作。

web端调用iOS

web端调用iOS,需要与iOS程序猿共同商定[self.webView.configuration.userContentController addScriptMessageHandler:self name:@"showMobile"];比如我和前端商定我将监听showMobile键传递的参数。可以传递空的,也可以传递字符串甚至字段。

web端要做的事情

window.webkit.messageHandlers.***.postMessage()

* 是商定的的key,上面是模板,直接copy过去,不会报错

//传递空
window.webkit.messageHandlers.showMobile.postMessage(null)
//传递字符串
window.webkit.messageHandlers.showMobile.postMessage("123") 
//传递数组
window.webkit.messageHandlers.showMobile.postMessage(['1', '2','3'])
//传递字典
window.webkit.messageHandlers.showMobile.postMessage({4: { 'windowID': 10004 } })

iOS 要做的事情

需要监听来自web端发过来的消息

#pragma mark --WKScriptMessageHandler
- (void)userContentController:(WKUserContentController *)userContentController didReceiveScriptMessage:(WKScriptMessage *)message{
NSLog(@"-----------%@",message.body);

if ([message.name isEqualToString:@"iOS"]) {
        NSDictionary *dict = message.body;
        //todo
}
}

以上,iOS与web交互完成

附加:监听title变化(KVO)

URL ,进度条变化同理

这里的title是wkWebView里面的title@property (nullable, nonatomic, readonly, copy) NSString *title;

[self.webView addObserver:self forKeyPath:@"title" options:NSKeyValueObservingOptionNew context:nil];
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context {

    if (object == self.webView && [keyPath isEqualToString:@"title"]) {
        //todo
    }
}

附加:关于window.XXX.functionName

这条说明是安卓那边说的,他们安卓调用方法就是这种格式调用的。window.ABC.getId(),而不是window.getId()和getId()可能安卓开发早,web前端都定义好了,如果让web前端改的话很麻烦。实话,就让前端改改就行,两套,这个写虽然是这么写过,写完后web端改写过,这个用法就没用过了。

//这是一条定义好的js格式,它的调用方法是:window.YiDao.getJSessionId()
NSString *Str = @"var YiDao = {}; (function initialize() {YiDao.getJSessionId = function () { return 'A3AB6839629D3B6F660452B6DFB47728';};})();";

你可以写成这样子

#define Js @"var YiDao = {}; (function initialize() {YiDao.%@ = function () { return '%@';};})(); "
NSString *Str = [NSString stringWithFormat:Js1,@"getId",@"value"];
//window.YiDao.getId()
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值