如何在目标 C 中使用 JS 上下文设置对象



我正在尝试使用这个用 Swift 编写的教程在 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)!)

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

//
//  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>

最新更新