swift2 Swift 2.0 NSURL连接发送同步请求

niknxzdl  于 2022-11-06  发布在  Swift
关注(0)|答案(1)|浏览(157)

我正在使用下面的代码来检查互联网连接。它工作正常,但在Swift 2.0更新后,我现在看到一个错误行var data = NSURLConnection.sendSynchronousRequest(request, returningResponse: &response, error: nil) as NSData?说额外的参数'错误'在调用。

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
}

你知道我该把它改成什么吗?谢谢

xsuvu9jc

xsuvu9jc1#

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

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

他们已经删除了error参数,如果请求失败,方法现在抛出一个ErrorType

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

但是,您不应使用此方法:从iOS 9和OS X 10.11开始,它被弃用,取而代之的是NSURLSession

相关问题