Swift 2.0 NSURLConnection sendSynchronousRequest

时间:2015-09-19 13:04:53

标签: xcode nsurlconnection swift2 nsurlrequest reachability

我正在使用以下代码检查互联网连接。它工作正常,但在Swift 2.0更新后,我现在在行>>> mult(5,-3) -15 >>> mult(-10,-3) 30 >>> mult(5,3) 15 上看到一个错误,说出额外的参数'错误'在电话中。

var data = NSURLConnection.sendSynchronousRequest(request, returningResponse: &response, error: nil) as NSData?

你有什么想法我应该改变它吗? 感谢

1 个答案:

答案 0 :(得分:6)

如果你查看苹果文档(https://developer.apple.com/library/ios/documentation/Cocoa/Reference/Foundation/Classes/NSURLConnection_Class/#//apple_ref/occ/clm/NSURLConnection/sendSynchronousRequest:returningResponse:error :),你会看到定义改为:

class func sendSynchronousRequest(_ request: NSURLRequest,
            returningResponse response: AutoreleasingUnsafeMutablePointer<NSURLResponse?>) throws -> NSData

如果请求失败,他们已经删除了错误参数,并且该方法现在抛出ErrorType。所以这应该有效:

do {
    let data = try NSURLConnection.sendSynchronousRequest(request, returningResponse: &response)
} catch (let e) {
    print(e)
}

但是你不应该使用这种方法:自iOS 9和OS X 10.11以来,它已被弃用,而不赞成NSURLSession