iOS h5与原生态混编

h5与原生态混编,一般情况下是在VC中插入一个webview,在webview(网上第三方比较好的WKWebView网页视图)中加载h5的地址url,使用的功能大部分主要分为:

1、原生oc调用js 

在网页加载完成之后,在成功回调方法中:

- (void)webViewDidFinishLoad:(UIWebView *)webView{
    NSString *jsStr = [NSString stringWithFormat:@"showAlert('%@')",@"在JS中Alert弹出的message"];
    [_webView stringByEvaluatingJavaScriptFromString:jsStr];
}
或者用JavaScriptCore库

- (void)webViewDidFinishLoad:(UIWebView *)webView{
    JSContext *context = [self.webView valueForKeyPath:@"documentView.webView.mainFrame.javaScriptContext"];
    NSString *textJS = @"showAlert('在JS中Alert弹出的message')";
    [context evaluateScript:textJS];
}

2、js调用原生oc 

使用JavaScriptCore库

- (void)webViewDidFinishLoad:(UIWebView *)webView{
    JSContext *context = [webView valueForKeyPath:@"documentView.webView.mainFrame.javaScriptContext"];
    context[@"js_share"] = ^{
        NSArray *arg = [JSContext currentArguments];
        if(arg && arg.count){
            JSValue *value = arg[0];
            NSString *string = value.toString;
            NSData *data = [string dataUsingEncoding:NSUTF8StringEncoding];
            NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:nil];
            [self shareButtonAction:dict];
        }
    };
}


 3、原生oc通过代理监听url

- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType{
    NSLog(@"%@", request.URL);
    if([request.URL.absoluteString hasSuffix:@"/login"]){
        LoginViewController *vc = [CommonMethod getVCFromNib:[LoginViewController class]];
        [self.navigationController pushViewController:vc animated:YES];
        [self.webView reload];
        return NO;
    }
}

最后如何清除webview的缓存

//清除cookie
NSHTTPCookie *cookie;
NSHTTPCookieStorage *storage = [NSHTTPCookieStorage sharedHTTPCookieStorage];
for (cookie in [storage cookies]){
    [storage deleteCookie:cookie];
}

//清除UIWebView的缓存
[[NSURLCache sharedURLCache] removeAllCachedResponses];
NSURLCache * cache = [NSURLCache sharedURLCache];
[cache removeAllCachedResponses];
[cache setDiskCapacity:0];
[cache setMemoryCapacity:0];


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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值