Tuesday, March 17, 2015

iOS: How to Send Asynchronous Requests

Many of the applications we build often have to fetch some sort of data through the network. While there are a number of ways one could fetch the data in our iOS application and a number of networking libraries available, it is still useful to understand how NSURLConnection actually works.

Step #1:
Need to have your class to conform to the NSURLConnectionDelegate protocol and declare a var to store the response data

Step #2:
Implement the NSURLConnectionDelegate protocol methods

Step #3:
Create an instance of NSURLRequest and NSURLConnection to kick off the request

In Step#1, when you class conforms to the NSURLConnectionDelegate protocol, it means that your class will need to implement all the required methods, which takes you to Step#2.
The idea is that when you kick off the request in Step #3, you want to be notified of events that will happen such as when the response comes back, and need to handle them appropriately.


Step #1:
Within the class that you will be using NSURLConnection, specify in the header file that it conforms to the NSURLConnectonDelegate protocol. Also, declare an instance variable  for holding the response data.





Step #2:
Next, implement the NSURLConnection protocol methods

















Step #3
Now, we are finally ready to perform the asynchronous request.
Let's start by creating an instance of NSURLRequest, and assign it to the URL.  Next, create an instance of a NSURLConnection and call the initWithRequest method, passing it your NSURLRequest.




After the NSURLRequest is dispatched and the request is handled, the callback handler, didReceiveResponse will be invoked to indicate that the server has responded. Then, the callback handler, connection:didReceiveData will be invoked. This is where you will append the new data to the instance variable you declared.  In connectionDidFinishLoading callback is invoked when the request is complete and the data has been received, so you can parse the response data and do whatever you want to do with the data.  That's all there's to it!

In the next blog post, I will cover how to send an asynchronous request using NSURLSession and Blocks!

No comments: