无法使用参数列表调用 Swift 2 中的 'sendAsynchronousRequest'

Cannot invoke 'sendAsynchronousRequest' in Swift 2 with an argument list

我目前正在重写部分 Swift 1.2 代码以与 Swift 2.0 兼容。实际上我不知道对 "sendAsynchronousRequest" 进行了哪些更改 - 目前我所有的请求都失败了

NSURLConnection.sendAsynchronousRequest(request, queue: queue, completionHandler:{ (response: NSURLResponse!, data: NSData!, error: NSError!) -> Void in})

Cannot invoke 'sendAsynchronousRequest' with an argument list of type '(NSURLRequest, queue: NSOperationQueue, completionHandler: (NSURLResponse!, NSData!, NSError!) -> Void)'

你知道哪里出了问题吗?

问题似乎出在完成块中的隐式解包选项上。只需将其设为可选即可,它应该可以正常工作,

NSURLConnection.sendAsynchronousRequest(request, queue: NSOperationQueue.mainQueue()) { (response: NSURLResponse?, data: NSData?, error: NSError?) in
  let string = NSString(data: data!, encoding: NSISOLatin1StringEncoding)
  print("Response \(string!)")
}

使用Swift 1.2和Xcode 6.3,sendAsynchronousRequest:queue:completionHandler:的签名是:

class func sendAsynchronousRequest(request: NSURLRequest,
    queue: NSOperationQueue!,
    completionHandler handler: (NSURLResponse!, NSData!, NSError!) -> Void)

使用 Swift 2 和 Xcode 7 beta,但是,sendAsynchronousRequest:queue:completionHandler: 的签名已更改,现在是:

// Note the non optionals, optionals and implicitly unwrapped optionals differences
class func sendAsynchronousRequest(request: NSURLRequest,
    queue: NSOperationQueue,
    completionHandler handler: (NSURLResponse?, NSData?, NSError?) -> Void)

因此,转向 Swift 2 和 Xcode 7 beta,您将必须更改 completionHandler 参数实现并确保您的 queue 参数是非可选。

因为 NSURLConnection.sendAsynchronousRequest 在 iOS 中被弃用 9. 应该使用 NSURLSession public func dataTaskWithRequest(request: NSURLRequest, completionHandler: (NSData?, NSURLResponse?, NSError?) -> Void) -> NSURLSessionDataTask

swift 3

    let url:URL? = URL(string:location)
    if url == nil {
        print("malformed url : \(location)")
    }

    NSURLConnection.sendAsynchronousRequest(URLRequest(url:url!),
        queue: OperationQueue.main)
    { (response: URLResponse?, data: Data?, error: Error?) -> Void in

    }