Home > Web Front-end > JS Tutorial > How to realize the interaction between OC and JS

How to realize the interaction between OC and JS

零到壹度
Release: 2018-04-13 16:44:34
Original
1739 people have browsed it

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

First type: JS passes values ​​to OC, using JavaScriptCore.framework.

oc code

#import <JavaScriptCore/JavaScriptCore.h>
Copy after login
- (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);
        }
    };
}
Copy after login

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);
}
Copy after login

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.


Second type: JS passes value to OC, using custom URL method.

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;
}
Copy after login

JS code

function QMAction(at, id, subject, el) {
    window.location.href="objc://"+":/"+subject+":/"+id;
}
Copy after login

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:

Interaction between OC and JS

Interaction between OC and JS

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!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template