我想在 Swift 2 中创建一个从 URL 获取数据并使用 NSURLSession 将其作为 JSON 对象返回的函数。起初,这似乎很简单。我写了以下内容:
func getJson(url:NSURL, completeWith: (AnyObject?,NSURLResponse?,NSError?)->Void) -> NSURLSessionTask? {
let session = NSURLSession.sharedSession()
let task = session.dataTaskWithURL(url) {
(data:NSData?, response:NSURLResponse?, error:NSError?) -> Void in
if error != nil {
completeWith(nil, response, error)
}
if let data = data {
do {
let object:AnyObject? = try NSJSONSerialization.JSONObjectWithData(data, options: .AllowFragments)
} catch let caught as NSError {
completeWith(nil, response, caught)
}
completeWith(object, response, nil)
} else {
completeWith(nil, response, error)
}
}
return task
}
但是,这不会编译,因为完成块没有声明“抛出”。确切的错误是Cannot invoke 'dataTaskWithURL' with an argument list of type '(NSURL, (NSData?, NSURLResponse?, NSError?) throws -> Void)'
。即使我在do/catch
声明中发现了所有错误,Swift 仍然希望将 NSError 向上传播。我能看到的唯一方法是使用try!
,如下所示:
if let data = data {
let object:AnyObject? = try! NSJSONSerialization.JSONObjectWithData(data, options: .AllowFragments)
completeWith(object, response, nil)
} else {
completeWith(nil, response, error)
}
现在一切都编译得很好,但是我丢失了NSJSONSerialization.JSONObjectWithData
.
有没有我可以捕获可能抛出的 NSErrorNSJSONSerialization.JSONObjectWithData
并将其传播到完成块而不修改完成块的签名?