Communication between javascript and Objective-c (

2019-06-02 05:24发布

I know the way to communicate between iOS and javascript is to create fake URLs in JS and append a string which will be used as parameter to the Objective-C code and parse that URL in this delegate method:

-(BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType

Then send the return value by calling the native method stringByEvaluatingJavaScriptFromString again with parameter callID.

But I want to, just like Android, directly call Objective-C methods from JS and get a return value. Instead of needing to write any method in JavaSCript to get the return value. Actually we have JS code already. It works perfectly while communicating with Android.

Are there any tricks to solve my problem that will be approved on the AppStore?

3条回答
SAY GOODBYE
2楼-- · 2019-06-02 06:10

If i understood your question properly that you want to invoke Objective-c method from Java script then below is the example which i have referred from Apple Documentation:-

Let’s look at a sample class. In this case, we will create an Objective-C address book class and expose it to JavaScript. Let’s start with the class definition:

@interface BasicAddressBook: NSObject {
}
+ (BasicAddressBook *)addressBook;
- (NSString *)nameAtIndex:(int)index;
@end

Now we’ll write the code to publish a BasicAddressBook instance to JavaScript:

BasicAddressBook *littleBlackBook = [BasicAddressBook addressBook];

id win = [webView windowScriptObject];
[win setValue:littleBlackBook forKey:@"AddressBook"];

Once you expose these methods to JavaScript (described at the end of this section), you should be able to access your basic address book from the JavaScript environment and perform actions on it using standard JavaScript functions.

Now, let’s make an example showing how you can use the BasicAddressBook class instance in JavaScript. In this case, we’ll print the name of a person at a certain index in our address book:

function printNameAtIndex(index) {
    var myaddressbook = window.AddressBook;
    var name = myaddressbook.nameAtIndex_(index);
    document.write(name);
}
查看更多
闹够了就滚
3楼-- · 2019-06-02 06:17

You can call javascript methods from objective C using simple steps.

Please go through this also see the Apple Documentation

查看更多
可以哭但决不认输i
4楼-- · 2019-06-02 06:26

There is no built-in method to do this, however you can use a library such as WebViewJavascriptBridge: https://github.com/marcuswestin/WebViewJavascriptBridge.

Even if there were a built-in solution, there are no standards for this. As such it wouldn't work the same way as it does on Android either way. Communicating with Obj-C code means that you're moving away from the browser and on to platform specific implementations which, by nature, vary between platforms.

查看更多
登录 后发表回答