现在原生端与JS交互是非常常见,项目中刚好有些详情页面需要与JS交互,同时评论在原生请求,JS端显示评论的内容。
是滴,今天主角就是它--UIWebView.
UIWebView内置一个方式可以执行JavaScript代码,因此OC调用JS比较方便点
- (nullable NSString *)stringByEvaluatingJavaScriptFromString:(NSString *)script;
OC部分:
//以下的方法名一定要与JS的方法名对应,这是oc调取JS的方法
NSString *nike = NikeName;
NSString *head = HEADICON;
NSString *str = [NSString stringWithFormat:@"alertSendMsg('%@','%@','%@')",nike,head,text];
//这个是多参的方法
[webView stringByEvaluatingJavaScriptFromString:str];
//这个是无参的方法
[webView stringByEvaluatingJavaScriptFromString:@"alertMobile()"];
//这个是一个参数的方法
[webView stringByEvaluatingJavaScriptFromString:@"alertName('冯大大')"];
JS部分:
function alertMobile() {
alert('我是上面的小黄 手机号是:13300001111')
}
function alertName(msg) {
alert('你好 ' + msg + ', 我也很高兴见到你')
}
function alertSendMsg(num,msg) {
alert('这是我的手机号:' + num + ',' + msg + '!!')
}
接下来是JS调用OC方法
UIWebView 中的delegate中的方法
- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType {
//OC调用JS是基于协议拦截实现的 下面是相关操作
NSString *absolutePath = request.URL.absoluteString;
NSString *scheme = @"rrcc://";
if ([absolutePath hasPrefix:scheme]) {
NSString *subPath = [absolutePath substringFromIndex:scheme.length];
if ([subPath containsString:@"?"]) {//1个或多个参数
if ([subPath containsString:@"&"]) {//多个参数
NSArray *components = [subPath componentsSeparatedByString:@"?"];
NSString *methodName = [components firstObject];
methodName = [methodName stringByReplacingOccurrencesOfString:@"_" withString:@":"];
// SEL sel = NSSelectorFromString(methodName);
NSString *parameter = [components lastObject];
NSArray *params = [parameter componentsSeparatedByString:@"&"];
if (params.count == 2) {
}
} else {//1个参数
NSArray *components = [subPath componentsSeparatedByString:@"?"];
NSString *methodName = [components firstObject];
methodName = [methodName stringByReplacingOccurrencesOfString:@"_" withString:@":"];
NSString *parameter = [components lastObject];
if ([parameter isEqualToString:@"comment"]) {
}
}
} else {//没有参数
// NSString *methodName = [subPath stringByReplacingOccurrencesOfString:@"_" withString:@":"];
// SEL sel = NSSelectorFromString(methodName);
//
// if ([self respondsToSelector:sel]) {
// [self performSelector:sel];
// }
}
}
return YES;
}
JS 中对应的方法
//JS响应方法列表
function btnClick1() {
location.href = "rrcc://showMobile"
}
function btnClick2() {
location.href = "rrcc://showName_?xiaohuang"
}
function btnClick3() {
location.href = "rrcc://showSendNumber_msg_?13300001111&go climbing this weekend"
}
JS与OC之间的交互已经完成。