Making Http Requests in Swift

If you know Objective-C, you must be familiar with the way of making http requests. The process is quite similar in Swift, however, having just a syntax change. Anyone who is new to this platform and is 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.

Synchronous Calls(Updated for Swift 2.0):

1
2
3
4
5
6
7
8
9
10
11
12
let urlString = "http://api.shephertz.com" // Your Normal URL String
let url = NSURL(string: urlString)// Creating URL
let request = NSURLRequest(URL: url!) // Creating Http Request
let response: AutoreleasingUnsafeMutablePointer<NSURLResponse?>=nil
// Sending Synchronous request using NSURLConnection
do {
let responseData = try NSURLConnection.sendSynchronousRequest(request, returningResponse: response) //Converting data to String
let responseStr:NSString = NSString(data:responseData, encoding:NSUTF8StringEncoding)!
} catch (let e) {
print(e)
// You can handle error response here
}

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
let urlString = "http://api.shephertz.com" // Your Normal URL String
let url = NSURL(string: urlString)// Creating URL
let request = NSURLRequest(URL:url!)// Creating Http Request
 
// Creating NSOperationQueue to which the handler block is dispatched when the request completes or failed
let 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
{
print(error!.description)
}
else
{
let responseStr:NSString = NSString(data:responseData!, encoding:NSUTF8StringEncoding)!
}
})

Using Delegate Pattern:

1
2
3
4
5
let urlString = "http://api.shephertz.com" // Your Normal URL String
let url = NSURL(string: urlString)// Creating URL
let request = NSURLRequest(URL: url!)// Creating Http Request
//Making request
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
5
func connection(connection: NSURLConnection, didReceiveResponse response: NSURLResponse)
{
//Will be called when
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
func connection(connection: NSURLConnection, didReceiveData _data: NSData)
{
NSLog("didReceiveData")
// Appending data
self.data.appendData(_data)
}
 
func connectionDidFinishLoading(connection: NSURLConnection)
{
NSLog("connectionDidFinishLoading")
let 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.

get started Making Http Requests in Swift

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 *


nine × 8 =

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>