PhoneGap.exec () passes objects between JS and Obj-C

The only way I found passing objects between JS and Obj-C is by encoding the JS object using JSON.stringify () and passing the json string to PhoneGap.exec

PhoneGap.exec('Alarm.update',JSON.stringify(list)); 

... and rebuild the object in Obj-C:

 NSString *jsonStr = [arguments objectAtIndex:0]; jsonStr = [jsonStr stringByReplacingOccurrencesOfString:@"\\\"" withString:@"\""]; jsonStr = [NSString stringWithFormat:@"[%@]",jsonStr]; NSObject *arg = [jsonStr JSONValue]; 

It is right? Is there a better / correct / official way to do this?

+4
source share
2 answers

I think this is the best way to do this, if not the only way.

Calling PhoneGap.exec just takes the NSDictionary objects under the covers, so I don’t see a better way to handle it.

most methods are structured as

 - (void)someMethod:(NSArray*)arguments withDict:(NSDictionary*)options { } 
+3
source

PhoneGap.exec was designed for simple types. Your path is in order, in turn you can just pass your only object (it will work for only one object, see the footer about how we marshal the command), and it should be in the parameter dictionary for the command. Then, on the Objective-C side, use key encoding to automatically populate your custom dictionary object.

eg. MyCustomObject * blah = [MyCustomObject new]; [blah setValuesForKeysWithDictionary: options];

If you are interested in how PhoneGap.exec works, read on ...

* --------- *

For PhoneGap.exec, javascript arguments are bound to a URL.

For the JS command: PhoneGap.exec ('MyPlugin.command', 'foo', 'bar', 'baz', {mykey1: 'myvalue1', mykey2: 'myvalue2'});

Final command URL: Gap: //MyPlugin.myCommand/foo/bar/baz/mykey1 = myvalue1 & mykey2 = myvalue2

It will be processed and converted on the Objective-C side. foo, bar, baz are placed in an array of arguments, and query parameters are placed in the parameter dictionary. It will look for a class called "MyPlugin" and will call the "myCommand" selector using an array of arguments and options as parameters.

For more information see phonegap.js, look at PhoneGap.run_command

+9
source

All Articles