iOS和JS之间的交互

来源:互联网 发布:获取httppost请求数据 编辑:程序博客网 时间:2024/06/02 03:35

iOS调用JS的方法:

    //js方法名+参数    NSString* jsCode = [NSString stringWithFormat:@"initCarLicenseInfo('%@')",object];        //调用html页面的js方法    [webView stringByEvaluatingJavaScriptFromString:jsCode];

JS调用iOS的方法:

这里iOS通过拦截H5触发的alert来实现调用,H5触发一个alert弹窗,将要调用的iOS方法名作为弹窗内容,iOS这边通过以下方法拦截这个弹窗,获取到方法名称,然后实现调用

@interface UIWebView (JavaScriptAlert)- (void)webView:(UIWebView *)sender runJavaScriptAlertPanelWithMessage:(NSString *)message initiatedByFrame:(CGRect *)frame;@end

@implementation UIWebView (JavaScriptAlert)- (void)webView:(UIWebView *)sender runJavaScriptAlertPanelWithMessage:(NSString *)message initiatedByFrame:(CGRect *)frame {    if ([message isEqualToString:kShowTakePhotoButton]) {        [[NSNotificationCenter defaultCenter] postNotificationName:kShowTakePhotoButton object:message];    }    else if([message isEqualToString:kHideTakePhotoButton]) {        [[NSNotificationCenter defaultCenter] postNotificationName:kHideTakePhotoButton object:message];    }    else    {        [DXCommon showAlertMessage:message];    }    NSLog(@"h5 message = %@",message);}@end

只要将以上类别导入到iOS工程中去就OK了,方法的实现是app工具自己的情况去实现,例如这里我拦截到kShowTakePhotoButton和kHideTakePhotoButton的时候分别抛出通知调用相应的方法,并且没有弹框,其他时候正常弹框;


实现类似微信里面浏览H5:

加载H5的并使用原生导航栏的时候,我们通过webView.canGoBack来判断是否是返回到最后一级页面,如果不是最后一级,添加关闭按钮(实现导航控制器pop),而返回按钮实现[webViewgoBack];方法来实现返回上一级页面,否则导航控制器pop;



0 0
原创粉丝点击