iOS h5与原生态混编

Posted Eric博客

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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];


以上是关于iOS h5与原生态混编的主要内容,如果未能解决你的问题,请参考以下文章

flutter与原生混编(iOS)

RN系列:Android原生与RN如何交互通信

iOS原生App与H5页面交互笔记

iOS原生与H5交互

iOS原生与H5交互WKWebView

H5与原生APP交互方式 (IOS及安卓)