更新到Swift 2.0后,NSURLConnection抛出

时间:2015-06-14 15:05:18

标签: swift try-catch nsurlconnection

在Swift 2.0 Update之前,这段代码非常适合用PHP脚本从服务器上下载我的JSON文件:

let url = NSURL(string: webAdress)
let cachePolicy = NSURLRequestCachePolicy.ReloadIgnoringLocalAndRemoteCacheData
var request = NSMutableURLRequest(URL: url!, cachePolicy: cachePolicy, timeoutInterval: 5.0)

var response: NSURLResponse? = nil
var error: NSError? = nil
let reply = NSURLConnection.sendSynchronousRequest(request, returningResponse:&response, error:&error)

更新后Xcode要求我做一些更改。我做了,代码没有错误,但它总是抛出......

    let url = NSURL(string: webAdress)
    let cachePolicy = NSURLRequestCachePolicy.ReloadIgnoringLocalAndRemoteCacheData
    let request = NSMutableURLRequest(URL: url!, cachePolicy: cachePolicy, timeoutInterval: 5.0)

    var response: NSURLResponse? = nil
    var reply = NSData()
    do {
    reply = try NSURLConnection.sendSynchronousRequest(request, returningResponse:&response)
    } catch {
        print("ERROR")
    }

期待您的解决方案!

2 个答案:

答案 0 :(得分:6)

以下是使用新NSURLSession的示例 - 显然在iOS 9中已弃用NSURLConnection。

let url = NSURL(string: webAddress)
let request = NSURLRequest(URL: url!, cachePolicy: .ReloadIgnoringLocalAndRemoteCacheData, timeoutInterval: 5.0)

let session = NSURLSession.sharedSession()

session.dataTaskWithRequest(request, completionHandler: {(data, response, error) in
    print(data)
    print(response)
    print(error)
})?.resume()

我认为它非常干净,而且没有太多关于它的文档。如果您在使用此功能时遇到任何问题,请与我们联系。

答案 1 :(得分:1)

Maximilian嗨, 我有同样未解决的问题,Sidetalker使用NSURLSession.dataTaskWithRequest提出的解决方案不是你想要的,因为NSURLSession API是高度异步的(根据Apple文档),你在swift 1.2中实现的代码是同步的。 另一方面,NSURLConnection在iOS 9中已被弃用,因此您编写的代码可能无法构建,对吧?

我建议的解决方案是:

let url = NSURL(string: webAdress)
let request: NSURLRequest = NSURLRequest(URL: url!)
let config = NSURLSessionConfiguration.defaultSessionConfiguration()
let session = NSURLSession(configuration: config)
var responseCode = -1
let group = dispatch_group_create()
dispatch_group_enter(group)
session.dataTaskWithRequest(request, completionHandler: {(_, response, _) in
if let httpResponse = response as? NSHTTPURLResponse {
    responseCode = httpResponse.statusCode
}
dispatch_group_leave(group)
})!.resume()
dispatch_group_wait(group, DISPATCH_TIME_FOREVER)
//rest of your code...

如果现在可以,请告诉我