I’m new in Objective-c. I want to make an HTTPRequest to an API.
This works, I get my response in an NSData object. This response
is a json response. How can I parse my response to get a dictionary
with key: value format?
I used this code to get the data:
data = [NSURLConnection sendSynchronousRequest: req
returningResponse: nil
error: nil];
Thanks
Use NSJSONSerialization (iOS5+) to convert JSON strings to Cocoa objects (
NSDictionaryin your case) and vice-versa.PS : If you need to also support iOS versions before 5.0, namely where the
NSJSONSerializationis not available, there are third-party libraries out there, likeJSONKitfor example. You may then either always useJSONKitboth on iOS4 and iOS5, or your may test at runtime forNSJSONSerializationavailability and use it if available (but fallback toJSONKitif not).(For more details on cross-SDK development, like making and app compatible with iOS4 but being able to use iOS5 classes when available, see the SDK Compatibility Guide)
By the way, you should (must) avoid using synchronous URL requests. This will block your thread until it receives the response from the network. If you execute it on the main thread, your whole UI will be frozen until you receive the response, which can take several seconds in a mobile environment (where you don’t always have the best network coverage).
Prefer:
sendAsynchronousRequest:queue:completionHandler:method (iOS5+) that will execute the request in a background NSOperation,