Error trying to perform a GET request in swift 2.0

我与影子孤独终老i 提交于 2019-12-13 18:23:51

问题


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?


回答1:


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()
}


来源:https://stackoverflow.com/questions/32342428/error-trying-to-perform-a-get-request-in-swift-2-0

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!