Swift 2.0: Unable to call argument list like ... (HTTP request)

Since I upgraded to Xcode 7, I have a bug that I cannot fix. Here's the complete 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: "Can't call" dataTaskWithURL "with an argument list like" (NSURL, completeHandler: (NSData !, NSURLResponse !, NSError!) → Void) '"I've been looking everywhere for how to fix this, but, since Swift 2.0 is very new I haven't found any solution.

+3


source to share


1 answer


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

      

changed to

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

      

in iOS9. CompletionHandler is no longer optional, and all parameters in the completionHandler file are now options instead of implicitly expanded options.



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 just use data, response, error in

and then click the option for more details.

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

To solve your problem in the comments, please review this question .

+6


source







All Articles