尝试在Swift 2.0中执行GET请求时出错 [英] Error trying to perform a GET request in swift 2.0
问题描述
所以我试图在Swift 2.0中执行GET请求,并且从Swift 1.2迁移了几行代码后,我遇到了这个错误,我并没有真正理解如何绕过它/正确地迁移它
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.
该函数编写如下:
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()
}
此后,Xcode向我输出以下错误:
After this, Xcode outputs me the following error:
无法使用类型为((NSMutableURLRequest,completeHandler:(NSData !, NSURLResponse !, NSError!)-> Void)''的参数列表调用'dataTaskWithRequest'
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?
推荐答案
此代码应该有效.使用Swift,您需要让它决定变量的类型.请注意,我拿走了你的演员表.
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()
}
这篇关于尝试在Swift 2.0中执行GET请求时出错的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!