Objective-C NSURLConnection example

I am reading about RESTful a lot those days because I want to develop an app that needs to use a lot of different APIs and just sticking with the SDK of each one was not enough for what I aim to do. So the natural step was to look of how those SDKs implement the APIs so there was were I met NSURLConnection class.

NSURLConnection is a class from Objective-C that basically lets you establish a connection with a URI to get or post some data. To the grain:

Asynchronous example

1. Have our class conform to the NSURLConnectionDelegate protocol and declare a var to store the response data

2. Implement the NSURLConnectionDelegate protocol methods

3. Create an instance of NSURLRequest and NSURLConnection to kick off the request

The idea is that when you kick off the request in Step 3, you want to be notified of certain events that will happen, such as when the response comes back. And you’ll be handling such events via methods you implement in Step 2. In Step 1, you’re basically telling the system that you intend handle those NSURLConnection events.

Step 1.

In the class you’ll be using NSURLConnection, specify in the header file that it conforms to the NSURLConnectionDelegate protocol. Also declare an instance variable to hold the response data.

 

Step 2.

Next, in the implementation file, you’ll implement the NSURLConnection protocol methods. In the comments in the code block below, you can see what each protocol method is used for:

 

Step 3.

Now you’re finally ready to perform the asynchronous request. Create an instance of NSURLRequest, assign it the URL. Next, create an instance of a NSURLConnection and call the initWithRequest method, passing in your NSURLRequest.

Step 4.

What should happen is when your request is fired in Step 3, your handler, connection:didReceiveResponse will be hit first, indicating that the server has responded. Then the handler, connection:didReceiveData: will be hit several times. This is where you’ll append the latest data to the response data variable you declared in Step 1. Then finally, connectionDidFinishLoading: will be hit and you can parse the response data variable.

If you want to do a synchronous request, you can use the sendSynchronousRequest method of NSURLConnection.

POST Request

To POST data, all you need to do is to use NSURLRequest like we did before previously, but this time you’ll set the HTTPMethod property to POST and you’ll assign the header fields and value in the body. Then we send it with NSURLConnection like before. The only difference is that this time, we’ll use an instance of NSMutableURLRequest because we need to modify and set it’s properties after initialization.