第一种:JS给OC传值,使用JavaScriptCore.framework。
oc 代码
#import <JavaScriptCore/JavaScriptCore.h>
- (void) webViewDidFinishLoad:(UIWebView *)webView{
JSContext *context = [webView valueForKeyPath:@"documentView.webView.mainFrame.javaScriptContext"];
context[@"favQues"] = ^{
NSArray *a = [JSContext currentArguments];
for (id obj in a) {
NSLog(@"obj:%@",obj);
}
};
}
其中 favQues 是 JS 中返回数据的函数,obj 就是 JS 传给 OC 的值。
JS 代码
function QMAction(id, subject, el) {
favQues(id,subject,el);
}
其中 QMAction 是HTML中的方法,id、subject,el是传进去的参数,favQues 是返回数据的函数,必须与 OC 代码中的保持一致。
第二种:JS给OC传值,使用自定义URL方法。
OC 代码- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType{
NSString *requestUrlStr = [[request.URL absoluteString] stringByRemovingPercentEncoding];
if ([requestUrlStr hasPrefix:@"objc://"]) {
NSArray *a = [requestUrlStr componentsSeparatedByString:@"://"];
NSString *paramStr = a[1];
NSArray *a1 = [paramStr componentsSeparatedByString:@":/"];
if (a1.count > 0) {
NSLog(@"%@-%@",a1[1],a1[2]);
}else{
NSLog(@"没有参数");
}
return NO;
}
return YES;
}
JS 代码
function QMAction(at, id, subject, el) {
window.location.href="objc://"+":/"+subject+":/"+id;
}
其中 objc:// 是与后台商量好的自定义协议头 subject 和 id 是 JS 传给 OC 的值,通过 :/ 隔开。