Make a GET request with Swift, NSURLSession and NSURLSessionDataTask

Here’s how to Make a simple GET request in Swift using NSURLSession and NSURLSessionDataTask. First, we will create singleton that has access to a ‘network’ struct that has a computed property called session. We’ll also create an instance method called apiRequest(name:String, completionblock:(error:NSError, responseDictionary:NSDictionary)->()) in the singleton instance that has access to the network struct.

API.swift

public struct network {
    public var session:NSURLSession? {
    get {
        let sessionConfig = NSURLSessionConfiguration.defaultSessionConfiguration()
        sessionConfig.HTTPAdditionalHeaders = //Dictionary here
        return NSURLSession(configuration: sessionConfig)
    }
    }
}

class API {
    class var sharedInstance : API {
    struct Static {
        static let instance : API = API()
        }
        return Static.instance
    }

//name argument isn't used in this method, 

    func apiRequest(name:String, completionblock:(error:NSError, responseDictionary:NSDictionary)->()) {
        let session = network().session!;
        let task : NSURLSessionDataTask = session.dataTaskWithURL(NSURL(string:"https://url_here"),completionHandler: {(data: NSData!, response: NSURLResponse!, error: NSError!) -> Void in
            let JSON: AnyObject! = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.AllowFragments, error: nil)
            NSLog(JSON!.description)
            return
            })
        task.resume()
    }
}

In your ViewController.swift file or another file that references the API class use this:


API.sharedInstance.apiRequest("name", completionblock: {(error: NSError, responseDictionary: NSDictionary) -> () in
//Set variables and do further processing here
 })

1 thought on “Make a GET request with Swift, NSURLSession and NSURLSessionDataTask”

  1. so how would you incorporate cookies into this GET request if you were attempting to connect to a REST API?

Leave a Reply

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