Reputation: 1878
I'm writing an iPhone app that loads Menu data from a database in the cloud. I am using AFNetworking (specifically AFJSONRequestOperation) to download the data in appDelegate.
Everything works fine up until this point, but I also need the app to be able to load the menu when the app is offline. To handle this, I want to save the returned JSON data to disc after it is retrieved by the AFJSONRequestOperation call.
My initial strategy was to save the returned JSON as a string, but I can't find a way to get the string response from an AFJSONRequestOperation. It seems silly to make two calls to the web service (one to return a JSON object and the other to return text) although it would be straightforward. I'd like to know if there is a better or more efficient way to do this. I could skip the AFJSONRequest and go for a plain AFHttpRequest but then I would need to construct the JSON object manually.
Is there a better option than either of the two I've thought up? In my opinion, the right answer would involve a single call that constructs the JSON object and also allows me to have access to the original text response, but I am open to hearing alternatives.
Upvotes: 1
Views: 2073
Reputation: 42588
Don't save it as the JSON string level. AFNetworking will return the JSON as either an NSArray or an NSDictionary depending on your JSON structure.
You can just save the array or dictionary as a plist.
see -[NSDictionary writeToURL:atomically:]
or -[NSArray writeToURL:atomically:]
Upvotes: 4
Reputation: 9194
I would try NSJSONSerialization to save NSData to disk.
Example:
NSData *dataToSave = [NSJSONSerialization dataWithJSONObject:responseObject options:nil error:nil];
id jsonObject = [NSJSONSerialization JSONObjectWithData:dataToSave options:nil error:nil];
Another option would be to take your responseObject from AFNetworking. Presumably a well-formed NSDictionary and simply place it in NSUserDefaults for semi-persistent storage. You need to make sure you don't have any null values in your dictionary as NSUserDefaults does not play nicely with null values.
Upvotes: 1