Making Http Requests in Swift

If you know Objective-C, you must be familiar with the way of making http requests and Swift in comparison will only be a syntax change. But, the one who is new to this platform and trying to start with swift might be wondering ‘how to make http request in swift?’.
swift icon Making Http Requests in Swift
Here, I will  propose a few tips to answer the above question. Normally, there are two ways of making http calls, Synchronous and Asynchronous and we will discuss both, one-by-one.

In objective C, the http calls can be made using NSURL, NSURLRequest and NSURLConnection and same can be used in this case as well. So let’s start with Synchronous calls.


get started Making Http Requests in Swift

Synchronous Calls:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
var urlString = "http://api.shephertz.com" // Your Normal URL String
var url = NSURL.URLWithString(urlString)// Creating URL
var request = NSURLRequest(URL: url) // Creating Http Request
var response:AutoreleasingUnsafePointer<NSURLResponse?> = nil;
var error: AutoreleasingUnsafePointer<NSErrorPointer?> = nil;
// Sending Synchronous request using NSURLConnection
var responseData = NSURLConnection.sendSynchronousRequest(request,returningResponse: response, error:nil) as NSData
if error != nil
{
   // You can handle error response here
}
else
{
   //Converting data to String
    var responseStr:NSString = NSString(data:responseData, encoding:NSUTF8StringEncoding) 
}

If the response is in JSON format, you can parse it directly to NSArray / NSDictionary format as:

1
var responseDict: NSDictionary = NSJSONSerialization.JSONObjectWithData(responseData,options: NSJSONReadingOptions.MutableContainers, error:nil) as NSDictionary

Asynchronous Calls: 
Asynchronous calls can be made using delegate pattern or using completion handler as in Objective-C.

Using Completion Handler:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
var urlString = "http://api.shephertz.com" // Your Normal URL String
var url = NSURL.URLWithString(urlString)// Creating URL
var request = NSURLRequest(URL: url)// Creating Http Request
 
// Creating NSOperationQueue to which the handler block is dispatched when the request completes or failed
var queue: NSOperationQueue = NSOperationQueue()
 
// Sending Asynchronous request using NSURLConnection
NSURLConnection.sendAsynchronousRequest(request, queue: queue, completionHandler:{(response:NSURLResponse!, responseData:NSData!, error: NSError!) ->Void in
 
        if error != nil
        {
            println(error.description)
            self.removeActivityIndicator()
        }
        else
        {
            //Converting data to String
            var responseStr:NSString = NSString(data:responseData, encoding:NSUTF8StringEncoding)
         }
    })

Using Delegate Pattern:

1
2
3
4
5
var urlString = "http://api.shephertz.com" // Your Normal URL String
var url = NSURL.URLWithString(urlString)// Creating URL
var request = NSURLRequest(URL: url)// Creating Http Request
//Making request
var connection = NSURLConnection(request: request, delegate: self, startImmediately: true)

Here, keep startImmediately as true if, the connection has to begin with loading the data immediately, otherwise state it as false. If you pass false, the connection will not be scheduled with a run loop. You can then schedule the connection in the run loop and mode of your choice by calling scheduleInRunLoop(_ aRunLoop: NSRunLoop!,forMode mode: String!).

Now, you have made the request but you need to define delegates as well to get the response in this case.

In the above code, we passed delegate as self, so the containing class should confirm to the NSURLConnectionDataDelegate, and class should also define the following delegate functions:

1
2
3
4
func connection(connection: NSURLConnection!, didReceiveResponse response: NSURLResponse!)
{ //It says the response started coming
    NSLog("didReceiveResponse")
}

You should always define a global NSMutableData variable as:

1
var data = NSMutableData()

Well, there is a possibility that the data may come in chunks. If the data is being received in parts, then the chunks of data can be collected in the following delegate function and appended to the globally defined data variable.

1
2
3
4
5
6
7
8
9
10
11
12
13
func connection(connection: NSURLConnection!, didReceiveData _data: NSData!)
{ //This will be called again and again until you get the full response
    NSLog("didReceiveData")
    // Appending data
    self.data.appendData(_data)
}
 
func connectionDidFinishLoading(connection: NSURLConnection!)
{
 // This will be called when the data loading is finished i.e. there is no data left to be received and now you can process the data.
    NSLog("connectionDidFinishLoading")
    var responseStr:NSString = NSString(data:self.data, encoding:NSUTF8StringEncoding)
}

I have encapsulated the entire code in a sample project that can be downloaded from my github repo.

If you have any queries or need further assistance, please feel free to reach us at support@shephertz.com.

twitter Making Http Requests in Swiftfacebook Making Http Requests in Swiftgoogle Making Http Requests in Swiftlinkedin Making Http Requests in Swiftpinterest Making Http Requests in Swiftreddit Making Http Requests in Swiftstumbleupon Making Http Requests in Swifttumblr Making Http Requests in Swift

Leave a Reply

Your email address will not be published. Required fields are marked *


− 1 = two

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>