What is the best way to get data from the internet, compressed and composed by PHP, to an iOS app? Currently, the app reads a string formatted like this:
category1#object2#object3#object4~category2#object2#object3[…]
And that is split up by the #
's and ~
's.
Is there a better way to do this, both in the way the data is retrieved (the开发者_C百科 site it gets it from is open for everyone), and the way the data is formatted?
Use JSON:
{"category1":["object1", "object2", "object3", "object4"], "category2":["object1", "object2"]}
So say you had a PHP object or associative array, you'd be able to simply invoke json_encode
on it and be done with it.
On the iOS end, you'd want to use JSONKit to parse it.
The best thing about these two ends of the pipeline is that there is native support for them. For example, json_encode
can encode any PHP object to a readable JSON string, while JSONKit can parse a JSON object and store it in an NSDictionary
or NSArray
.
Heck, with JSONKit, it augments the capability (using categories on NSDictionary
and NSArray
) to convert NSDictionary
and NSArray
objects into JSON, so you can even have a two-way JSON communication pipeline.
(We do this with our games at Freeverse, the methodology is tried and tested.)
Instead of yet another JSON answer, I'm going to give some links on "Picking the best JSON library":
- Comparison of JSON Parser for Objective-C (JSON Framework, YAJL, TouchJSON, etc)
- Best JSON library to use when developing an iPhone application?
And now for the shameless plug for my own JSON parsing solution, JSONKit:
- What's the most efficient way of converting a 10 MB JSON response into an NSDictionary?
- Cocoa JSON parsing libraries, part 2
acani uses JSON too, but if you have a really long feed, XML is better because Apple has already built an asynchronous XML parsing library whereas the JSON library is synchronous. So, using the JSON library, you must wait for the complete JSON response to download and then to be parsed before accessing any of the elements. With the XML library, it starts parsing the XML before waiting for it to completely download, AND it calls a callback function after each element in the XML has finished getting parsed into an Objective-C object for immediate use. So, you can access the objects before the whole feed has been downloaded. So, for small feeds, use JSON (cause I love JSON, and it's easier). For large feeds, use XML. Hopefully, they'll come out with an asynchronous JSON solution soon.
Look at the Top Songs Xcode sample app for an example of how to use the XML library asynchronously.
精彩评论