本篇文章给大家分享的内容是如何实现oc与js的交互,有着一定的参考价值,有需要的朋友可以参考一下
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 代码中的保持一致。
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 的值,通过 :/ 隔开。
相关推荐:
以上就是如何实现OC与JS的交互的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号