无法使用参数列表在Swift 2中调用“sendAsynchronousRequest”

时间:2015-06-11 07:42:34

标签: swift swift2

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

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

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

你有什么想法有什么不对吗?

4 个答案:

答案 0 :(得分: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参数是非可选参数。

答案 1 :(得分:4)

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

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

答案 2 :(得分:2)

由于iOS 9中不推荐使用NSURLConnection.sendAsynchronousRequest,因此应使用NSURLSession public func dataTaskWithRequest(request: NSURLRequest, completionHandler: (NSData?, NSURLResponse?, NSError?) -> Void) -> NSURLSessionDataTask

答案 3 :(得分:0)

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

    }