简体   繁体   中英

How to pass an Object from Objective C to javascript

For passing the variable we are using UIWebView ' method stringByEvaluatingJavaScriptFromString:

And how can I pass an Object?

For passing an object from Obj-C to JS, you have no choice but to serialize and deserialize it. The most fitting data format would naturally be JSON. This tutorial will help you: http://www.raywenderlich.com/5492/working-with-json-in-ios-5

From your question I gather that you don't just want to talk to JavaScript but to the JavaScript context inside of a UIWebView. Sadly, you can't directly access the JSContext object of a UIWebView the way you can access it in Cocoa on the Mac. But if you just want to bridge from Obj-C to JavaScript WITHOUT using a UIWebView, you can so by shipping your own version of JavaScriptCore with your app. If you do that, you can move Obj-C and JS objects back and forth between the two worlds. This is a demo project that demonstrates this: https://github.com/jfahrenkrug/AddressBookSpy/blob/master/AddressBookSpy/AddressBookSpy/ABSEngine.m

I forked phoboslab's repo and updated it to the latest verson from WebKit (as of last friday). It is compatible with iOS 5 and 6 and includes the Objective-C to Javascript bridge to be featured in iOS 7 (no private frameworks or function used).

You can find the repo on GitHub at: https://github.com/darionco/JavaScriptCore-iOS

I also added a ZIP file to the repo containing the library (.a) and needed header files for convenience.

You can find a tutorial on how to use the bridge to pass objects around here: http://www.steamclock.com/blog/2013/05/apple-objective-c-javascript-bridge/

Cheers!

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