iOS web view 与 js 交互

移动应用中许多复杂的且经常改动的页面会使用H5进行代替native,这里就会使用到js和webview的交互

iOS里面,UIWebView提供了方法stringByEvaluatingJavaScriptFromString:使js和webview互通

这里我提供一种思路,仅供参考

1.加载js函数

 

var Test = {};
Test.platform = {
name: 'IOS'
};
// 返回App识别ID
Test.getAppId = function(){
    return '[AppId]';
};
// 返回用户Id
Test.getUserId = function(){
    return '[UserId]';
};
// 返回当前AppVersion
Test.getAppVersion = function(){
    return '[AppVersion]';
};
Test.open = function(str){
    setTimeout(function(){
               document.location = 'Test://open/'+str;
               },50);
};
window.Test = Test;

 

2.简单几个函数,加载前替换掉自己的value,

for (NSString *key in dict) {
        NSString *placekey = [NSString stringWithFormat:@"[%@]", key];
        NSString *value = [dict[key] stringValue];
        if (! value || [value isEqual:[NSNull null]]) {
            jsString = [jsString stringByReplacingOccurrencesOfString:placekey withString:@"null"];
        }else{
            jsString = [jsString stringByReplacingOccurrencesOfString:placekey withString:value];
        }
    }

 3.加入webview的js里面:

   [webView stringByEvaluatingJavaScriptFromString:jsString];

 当js调用native的操作时候,可以使用Test.open(firstViewController?paramter=123)
native的delegate将会调用:

- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType

这里的request.url将会是:

Test://open/firstViewController?paramter=123

 进入我们自己解析方法,对此url进行不同的解析和跳转

NSString *requestString = [[request URL] absoluteString];
    NSArray *components = [requestString componentsSeparatedByString:@"://"];

    if (components[0] && [components count] > 1) {//如果协议抬头为Test或者为其他则走自定义流程
        NSString *content = components[1];
        NSArray *controller = [content componentsSeparatedByString:@"/"];
        if (controller.count > 1 && [controller[0] isEqual:@"open"]) {//打开特定的controller
            [self openController:controller[1]];
        }
    }

    return NO;

 

转载于:https://www.cnblogs.com/OIMM/p/5938849.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值