I have some Objective-c code that makes an asynchronous (I think lol) call to a server, but I am not too sure, what is the correct way to handle the response that comes back from the server?
I do something like this:
NSURLRequest *urlRequest = [NSURLRequest requestWithURL:url];
// ***************
// TODO: ok I dont really understand what this is
NSOperationQueue *queue = [[NSOperationQueue alloc] init];
// **************
[NSURLConnection sendAsynchronousRequest:urlRequest queue:queue completionHandler:^(NSURLResponse *response, NSData *data, NSError *error)
{
...
and because I am very new to Objective-C, I am not certain even where to look at how to get the values from the objects, or how to handle the NSData or the NSResponse objects.
I know my server sometimes sends back a JSON response and sometimes just a string like “ok”
Also, adding to my confusion is this tutorial:
according to which I should have a few separate functions like
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
or
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
So my question is what is the way to get the basic returned data from the 3 variables (error, response, data) from the request, and when should I implement the methods that the tutorial I mentioned suggests? It seems like the tutorial has a much more elegant solution…but I am not sure if its overkill.
Error
NSError has a unique little feature (especially inside blocks) where when a variable and its address are passed in as an argument (in this case, a simple NSError*), the method is expected to modify the object and return a useable instance in case of error. In normal use cases where no errors occur, this should be
nil, which we can log inside the completion handler part of the block:Response
NSURLResponse is not important in your case. As Apple puts it:
You would use an NSURLResponse for file downloads, and that’s about it. JSON is returned by an NSURLConnection object.
Data
Possibly the most important part of the whole deal. Your JSON response would be contained within this data, which means it has to be converted into a string, and then sent off to an interpreter so that we can pull actual ObjC objects out of the JSON values. Several widely used classes were built for just that including JSON Framework, JSONKit, and TouchJSON.
An NSOperationQueue, by the way, is much like a thread pool, but it takes the management role. NSOperationQueue objects are sent NSOperation objects, which are then added to its internal queue and executed on threads that are also managed by the NSOperationQueue object. They are now basically useless considering the advent of GCD in iOS 4.x, but in the case of legacy software support, they are useful for executing asynchronous (or synchronous, depending on whether the isConcurrent property is set on a submitted operation) tasks on background threads.