简体   繁体   中英

How to use JS Context SetObject in Objective C

I am trying to communicate between JS and ObjC using this tutorial which is written in Swift, but I am using 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)")
    }
}

And injecting the communication class in JS

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

How will I be doing this in Objective 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 file 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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM