Swift 2.0 : Cannot invoke with an argument list of type... (HTTP Request)

5.1k views Asked by At

Since I upgraded to Xcode 7 beta I have an error that I can't fix. Here's the full code from my DataManager.swift

import Foundation
var TopAppURL:String = String()
var numberAsked:String = String()

class DataManager {


class func getInfo(ID : String){
    TopAppURL = "http://sweetapi.com/?=\(ID)"
    numberAsked = ID
    }


class func loadDataFromURL(url: NSURL, completion:(data: NSData?, error: NSError?) -> Void) {
    var session = NSURLSession.sharedSession()
        // Use NSURLSession to get data from an NSURL
    let loadDataTask = session.dataTaskWithURL(url, completionHandler: { (data: NSData!, response: NSURLResponse!, error: NSError!) -> Void in
        if let responseError = error {
            completion(data: nil, error: responseError)
        } else if let httpResponse = response as? NSHTTPURLResponse {
            if httpResponse.statusCode != 200 {
                var statusError = NSError(domain:"com.raywenderlich", code:httpResponse.statusCode, userInfo:[NSLocalizedDescriptionKey : "HTTP status code has unexpected value."])
                completion(data: nil, error: statusError)
            } else {
                completion(data: data, error: nil)
            }
        }
    })

    loadDataTask.resume()
}

class func getDataFromSweetApiOk(success: ((IDdata: NSData!) -> Void)) {
    //1
    print("DataManager loads \(TopAppURL)")
    loadDataFromURL(NSURL(string: TopAppURL)!, completion:{(data, error) -> Void in
        //2
        if let urlData = data {
            //3
            success(IDdata: urlData)
        }
    })
}
}

So I got this error : "Cannot invoke 'dataTaskWithURL' with an argument list of type '(NSURL, completionHandler: (NSData!, NSURLResponse!, NSError!) -> Void)'" I searched everywhere how to fix this but like Swift 2.0 is very new, I didn't found any solution.

1

There are 1 answers

0
vrwim On BEST ANSWER
func dataTaskWithURL(_ url: NSURL,
   completionHandler completionHandler: ((NSData!,
                              NSURLResponse!,
                              NSError!) -> Void)?) -> NSURLSessionDataTask

has changed to

func dataTaskWithURL(_ url: NSURL,
   completionHandler completionHandler: (NSData?,
                              NSURLResponse?,
                              NSError?) -> Void) -> NSURLSessionDataTask?

in iOS9. The completionHandler no longer is optional, and all parameters in the completionHandler are now optionals instead of implicitly unwrapped optionals.

Now, to help with this in future changes to the optional system, try to avoid (data: NSData!, response: NSURLResponse!, error: NSError!) -> Void in, you can simply use data, response, error in and then option-click for more details.

This will remove bloat from your code, and thus improve readability.

To solve your problem in the comments, check out this question.