1. 程式人生 > >OC與JS互動

OC與JS互動

第一種: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 的值,通過 :/ 隔開。