如何在Objective C中使用JS Context SetObject

时间:2017-05-17 09:12:57

标签: ios objective-c swift xcode swift3

我正在尝试使用用Swift编写的tutorial在JS和ObjC之间进行通信,但我使用的是ObjC。

@objc protocol CommunicationProtocol: JSExport {
    static func callNativeFunction(_ mytext: String)
}

@objc class CommunicationClass: NSObject, CommunicationProtocol {
    class func callNativeFunction(_ mytext: String) {
        print("Native function called \(mytext)")
    }
}

在JS中注入通信类

ctx.setObject(unsafeBitCast(CommunicationClass.self, to: AnyObject.self), forKeyedSubscript: "SwiftBridge" as (NSCopying & NSObjectProtocol)!)

我将如何在Objective C中执行此操作

1 个答案:

答案 0 :(得分:1)

//
//  ViewController.m
//  ObjcTest
//
//  Created by Inder Kumar Rathore on 07/05/17.
//  Copyright © 2017 Inder Kumar Rathore. All rights reserved.
//

#import "ViewController.h"

#import <JavaScriptCore/JavaScriptCore.h>


@protocol CommunicationProtocol <JSExport>

+ (void)callNativeFunction:(NSString *)mytext;

@end


@interface CommunicationClass : NSObject<CommunicationProtocol>

@end


@implementation CommunicationClass

+ (void)callNativeFunction:(NSString *)mytext {
    NSLog(@"Hurray! Native method called:%@", mytext);
}

@end




@implementation ViewController {

    __weak IBOutlet UIWebView *webView;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    NSURL *url = [[NSBundle mainBundle] URLForResource:@"abc" withExtension:@"html"];
    [webView loadRequest:[NSURLRequest requestWithURL:url]];
}


- (void)webViewDidFinishLoad:(UIWebView *)webView {
    JSContext *ctxt = [webView valueForKeyPath:@"documentView.webView.mainFrame.javaScriptContext"];
    [ctxt setObject:[CommunicationClass class] forKeyedSubscript:@"SwiftBridge"];
}


@end

HTML文件abc.html

<!doctype html>
<html lang="en">

    <head>
        <meta charset="utf-8">
            <title>Web page</title>
            <script src="https://code.jquery.com/jquery-3.1.1.min.js"></script>
            <script type="text/javascript">
                function callNative(mytext) {
                    SwiftBridge.callNativeFunction(mytext);
                }

            function changeText(text) {
                $("#textfield").val(text);
            }
            $(function() {

              $("#textfield").on("keyup", function() {
                                 textChanged($("#textfield").val());
                                 });
              });
                </script>
            </head>

    <body>
        <input type="text" id="textfield" />
        <br/>

        <a onclick="callNative('hi from web!');" href="#">call native function</a>
    </body>

</html>