Swift 2.0 NSURLConnection sendSynchronousRequest

妖精的绣舞 提交于 2019-12-17 20:33:21

问题


I am using the code below to check for an internet connection. It was working correctly but after the Swift 2.0 update I now see an error on the line var data = NSURLConnection.sendSynchronousRequest(request, returningResponse: &response, error: nil) as NSData? saying extra argument 'error' in call.

class func isConnectedToNetwork()->Bool{

    var Status:Bool = false
    let url = NSURL(string: "http://google.com/")
    let request = NSMutableURLRequest(URL: url!)
    request.HTTPMethod = "HEAD"
    request.cachePolicy = NSURLRequestCachePolicy.ReloadIgnoringLocalAndRemoteCacheData
    request.timeoutInterval = 10.0

    var response: NSURLResponse?

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

    if let httpResponse = response as? NSHTTPURLResponse {
        if httpResponse.statusCode == 200 {
            Status = true
        }
    }

    return Status
}

Do you have any ideas what I should change it to? Thanks


回答1:


If you look at apples documentation (https://developer.apple.com/library/ios/documentation/Cocoa/Reference/Foundation/Classes/NSURLConnection_Class/#//apple_ref/occ/clm/NSURLConnection/sendSynchronousRequest:returningResponse:error:) you'll see that the definition changed to this:

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

They have removed the error parameter and the method throws now an ErrorType, if the request fails. So this should work:

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

However you shouldn't use this method: It's deprecated in favor of NSURLSession since iOS 9 and OS X 10.11.



来源:https://stackoverflow.com/questions/32668554/swift-2-0-nsurlconnection-sendsynchronousrequest

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!