gpt4 book ai didi

try-catch - 在 Swift 2 中,如何将 JSON 解析错误返回到完成 block ?

转载 作者:行者123 更新时间:2023-12-04 01:36:21 24 4
gpt4 key购买 nike

我想在 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
}

但是,这不会编译,因为完成块没有声明“throws”。确切的错误是 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 抛出的 NSError .

我是否可以捕获 NSJSONSerialization.JSONObjectWithData 可能引发的 NSError并将其传播到完成块而不修改完成块的签名?

最佳答案

我认为,您的捕获并不详尽,因此您需要这样的东西:

do
{
let object:AnyObject? = try NSJSONSerialization.JSONObjectWithData(data, options: .AllowFragments)
completeWith(object, response, nil)
} catch let caught as NSError {
completeWith(nil, response, caught)
} catch {
// Something else happened.
// Insert your domain, code, etc. when constructing the error.
let error: NSError = NSError(domain: "<Your domain>", code: 1, userInfo: nil)
completeWith(nil, nil, error)
}

关于try-catch - 在 Swift 2 中,如何将 JSON 解析错误返回到完成 block ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30837597/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com