Home > Article > Web Front-end > How to realize the interaction between OC and JS
This article shares with you how to realize the interaction between OC and JS. It has a certain reference value. Friends in need can refer to it
oc code
#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); } }; }
where favQues is the function that returns data in JS, and obj is what JS passes to OC value.
JS code
function QMAction(id, subject, el) { favQues(id,subject,el); }
QMAction is the method in HTML, id, subject, el are the parameters passed in, and favQues is the return data The functions must be consistent with those in the OC code.
OC code
- (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 code
function QMAction(at, id, subject, el) { window.location.href="objc://"+":/"+subject+":/"+id; }
where objc :// is the custom protocol header subject and id negotiated with the backend, which is the value passed to OC by JS, separated by :/.
Related recommendations:
The above is the detailed content of How to realize the interaction between OC and JS. For more information, please follow other related articles on the PHP Chinese website!