How to write SWIFT code to make HTTP GET request

Making HTTP and HTTPS requests in any application, client side or server side, is one of the first tasks that any developer needs to execute when an application needs to get data from server or send data to server. This is no different for iOS applications running on mobile devices like phones and/or tablets. There are lot of wonderful resources available to learn these concepts using Objective-C. The language has been around since the dawn of OSX.

SWIFT language is gaining more use in iOS development. In this blog I will show a very simple sample code that demonstrates how to make a HTTP code using SWIFT. I will not be going into lot of details about fundamentals behind how HTTP/HTTPS requests work in iOS. Apple has done a wonderful job in describing this in very detail in following articles.

Sample code showing how to use NSURLSession

In iOS there are other objects like NSURLConnection that can be used to make HTTP requests. But starting from iOS7.0, NSURLSession is preferred object to make HTTP requests. In this and any future blogs, I will stick to use of NSURLSession object unless something absolutely requires use of other objects.

    import Foundation
    public class ApiClient:NSObject, NSURLSessionDelegate,
    NSURLSessionTaskDelegate, NSURLSessionDataDelegate{
    var responseData:NSMutableData = NSMutableData()
    var requestStartTime:NSDate = NSDate()

    public func hearBeat(){
        print("heartBeat - Start")
        let url = NSURL(string:"https://www.google.com")
        print("Request url is: \(url)!")
        // Step0: Create request object.
        let request = NSMutableURLRequest(URL:url!)
        // Step1: Create configuration
        let configuration = NSURLSessionConfiguration.defaultSessionConfiguration()
        // Step2: Create session object with appropriate configuration, delegate and delegate queue
        let session = NSURLSession(configuration: configuration, delegate: self,
                delegateQueue: NSOperationQueue.mainQueue())
        // Step3: Create session task
        let sessionTask = session.dataTaskWithRequest(request)
        requestStartTime = NSDate()
        sessionTask.resume()
    }

    public func URLSession(session: NSURLSession, task: NSURLSessionTask,
                           didCompleteWithError error: NSError?) {
        // When session task is complete, this delegate method will be called.
        // If there is no error then NSError object will nil, otherwise NSError
        // will contain information about the error.
        if let errorInfo = error{
            print("Session error: \(errorInfo.description)")
        }
        else{
            print("Request - complete!")
            print("Total data downloaded - \(responseData.length) bytes")
            print("Total request time: \(-requestStartTime.timeIntervalSinceNow) seconds")
            // Now you can process the data.
        }
    }

    public func URLSession(session: NSURLSession, task: NSURLSessionTask,
        willPerformHTTPRedirection response: NSHTTPURLResponse,
        newRequest request: NSURLRequest,
        completionHandler: (NSURLRequest?) -> Void) {
        print("Redirecting request!")
        // For bypass redirect, create new URL request and assign it incoming
        // new request object. And then call completion handler.
        let newRequest:NSURLRequest? = request
        print(newRequest?.description)
        completionHandler(newRequest)
    }

    public func URLSession(session: NSURLSession, dataTask: NSURLSessionDataTask,
            didReceiveResponse response: NSURLResponse,
            completionHandler: (NSURLSessionResponseDisposition) -> Void) {
        print("Session received first response!")
        responseData = NSMutableData()
        // It is necessary to call completionHandler, otherwise request
        // will not progress one way or the other
        completionHandler(NSURLSessionResponseDisposition.Allow)
    }
    public func URLSession(session: NSURLSession, dataTask: NSURLSessionDataTask,
            didReceiveData data: NSData) {
        responseData.appendData(data)
    }

    public func URLSession(session: NSURLSession, dataTask: NSURLSessionDataTask,
            willCacheResponse proposedResponse: NSCachedURLResponse,
            completionHandler: (NSCachedURLResponse?) -> Void) {
        print("Session response caching!")
        completionHandler(proposedResponse)
    }
}

In this sample I have tried to add some debugging messages to show how the call flow works. This helps in understanding the order in which delegate methods are called. Based on this sample code, following output shows the flow of calls.

    heartBeat - Start
    Request url is: Optional(https://www.google.com)!
    Redirecting request!
    Optional({ URL: https://www.google.co.in/?gfe_rd=cr&ei=Vu5bVvDwMerI8Ae5n4GwAw }")
    Session received first response!
    Session response caching!
    Request - complete!
    Total data downloaded - 20767 bytes
    Total request time: 0.870199024677277 seconds

You can see from this output that when I tried to send GET request to https://www.google.com, the request got redirected to https://www.google.co.in. This happened because I executed the code from India. Google detected the location and redirected the call accordingly.

The sample code in this post has used default settings for underlying request and configuration settings. In subsequent posts, I will show how you can alter behavior of HTTP requests as per your requirements.

comments powered by Disqus

Blog Tags