6

我目前正在重写部分 Swift 1.2 代码以兼容 Swift 2.0。实际上我无法弄清楚对“sendAsynchronousRequest”进行了哪些更改 - 目前我所有的请求都失败了

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

无法使用类型为“(NSURLRequest,队列:NSOperationQueue,completionHandler:(NSURLResponse!,NSData!,NSError!)-> Void)”的参数列表调用“sendAsynchronousRequest”

你有什么想法吗?

4

4 回答 4

6

在 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参数是非可选的。

于 2015-06-12T09:00:48.413 回答
4

似乎问题在于您在完成块中的隐式未包装选项。让它成为可选的,它应该可以正常工作,

NSURLConnection.sendAsynchronousRequest(request, queue: NSOperationQueue.mainQueue()) { (response: NSURLResponse?, data: NSData?, error: NSError?) in
  let string = NSString(data: data!, encoding: NSISOLatin1StringEncoding)
  print("Response \(string!)")
}
于 2015-06-11T07:52:14.677 回答
2

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

于 2015-09-03T12:45:19.833 回答
0

迅速 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

    }
于 2016-11-12T23:19:55.637 回答