webview如何想要js和oc交互,需要使用代理方法 ,并且需要和后台协定规则
-(BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType{
NSString *url = request.URL.absoluteString;
NSLog(@"========%@",url);
NSString *urlString=request.URL.absoluteString;
//我们制定了一个协议,调用oc的方法都以hq://开头,后边跟着方法名
NSString *[email protected]"icocos:///";
//如果是我们自定义的协议hq://call
if ([urlString hasPrefix:scheme]) {
//取出scheme后边的路径
NSString *path=[urlString substringFromIndex:scheme.length];
//根据?区分出方法名 参数
NSArray *array=[path componentsSeparatedByString:@"?"];
NSLog(@"%@",array);
NSString *methodName=array.firstObject;
if (array.count == 2) {
NSString *str = [array.lastObject stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSDictionary *dict = [[NSString alloc] dictionaryWithJsonString:str];
[[NSUserDefaults standardUserDefaults]setObject:dict forKey:@"Wxpaydict"];
}
NSLog(@"-----------%@",methodName);
SEL method = NSSelectorFromString(methodName);
[self performSelector:method];
return NO;
}
return YES;
}
methodName就是你和后台协定的规则 方法名
NSString *[email protected]"icocos:///"; 前后台必须要一致
下面是js传参给oc 还是很麻烦的
NSArray *array=[path componentsSeparatedByString:@"?"];
NSLog(@"%@",array);
NSString *methodName=array.firstObject;
if (array.count == 2) {
NSString *str = [array.lastObject stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSDictionary *dict = [[NSString alloc] dictionaryWithJsonString:str];