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

How to realize the interaction between OC and JS

零到壹度
零到壹度Original
2018-04-13 16:44:341667browse

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>
- (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.


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;
}

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:

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!

Statement:
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