Ivan Cantarino
Ivan Cantarino

Reputation: 3246

Error trying to perform a GET request in swift 2.0

So I'm trying to perform a GET request in Swift 2.0, and after migrating a few lines of code from my Swift 1.2 I'm getting this error that I'm not really understanding how to bypass it / migrate it correctly.

The function is written as the following:

func performGetRequest(targetURL: NSURL!, completion: (data: NSData?, HTTPStatusCode: Int, error: NSError?) -> Void) {
    let request = NSMutableURLRequest(URL: targetURL)
    request.HTTPMethod = "GET"

    let sessionConfiguration = NSURLSessionConfiguration.defaultSessionConfiguration()

    let session = NSURLSession(configuration: sessionConfiguration)

    let task = session.dataTaskWithRequest(request, completionHandler: { (data: NSData!, response: NSURLResponse!, error: NSError!) -> Void in
        dispatch_async(dispatch_get_main_queue(), { () -> Void in
            completion(data: data, HTTPStatusCode: (response as! NSHTTPURLResponse).statusCode, error: error)
        })
    })


    task.resume()
}

After this, Xcode outputs me the following error:

Cannot invoke 'dataTaskWithRequest' with an argument list of type '(NSMutableURLRequest, completionHandler: (NSData!, NSURLResponse!, NSError!) -> Void)'

Have you ever came across this, or know how to fix-it?

Upvotes: 1

Views: 747

Answers (1)

Walter
Walter

Reputation: 5887

This code should work. With Swift, you need to let it decide what type a variable is as much as you can. Notice that I took out your casts.

    func performGetRequest(targetURL: NSURL!, completion: (data: NSData?, HTTPStatusCode: Int, error: NSError?) -> Void) {
    let request = NSMutableURLRequest(URL: targetURL)
    request.HTTPMethod = "GET"

    let sessionConfiguration = NSURLSessionConfiguration.defaultSessionConfiguration()

    let session = NSURLSession(configuration: sessionConfiguration)

    let task = session.dataTaskWithRequest(request, completionHandler: { (data, response, error) -> Void in
        dispatch_async(dispatch_get_main_queue(), { () -> Void in
            completion(data: data, HTTPStatusCode: (response as! NSHTTPURLResponse).statusCode, error: error)
        })
    })


    task.resume()
}

Upvotes: 0

Related Questions