问题描述
所以我想知道在将返回数据发送到以下命令之前如何检查返回数据是否包含标题。
guard let urls = URL(string: "https://api.drn1.com.au:9000/Nowplaying/\(stationurl)?uuid=\(MusicPlayer.uuid!)") else { return }
URLSession.shared.dataTask(with: urls) { ( data,_,_) in
// Based on the updated structs,you would no
// longer be decoding an array
if(data != nil){
let podcast = try! JSONDecoder().decode(Nowplayng.self,from: data!)
dispatchQueue.main.async{
// The array is stored under programs Now
completion(podcast.data.first!.track)
}
}
}
.resume()
}
因为根据Crashlytics,以下内容
let podcast = try! JSONDecoder().decode(Nowplayng.self,from: data!)
如果没有标题,则导致应用崩溃
podcast.data.first!.track.title
我从Crashlytics中得到的错误。
Fatal error: 'try!' expression unexpectedly raised an error: Swift.DecodingError.valueNotFound(Swift.String,Swift.DecodingError.Context(codingPath: [CodingKeys(stringValue: "data",intValue: nil),_JSONKey(stringValue: "Index 0",intValue: 0),CodingKeys(stringValue: "track",CodingKeys(stringValue: "title",intValue: nil)],debugDescription: "Expected String value but found null instead.",underlyingError: nil)): file /Users/russellharrower/Apps/vscroll/vscroll/Core/NowPlaying.swift,line 57
进一步检查后,我发现它说的是stringValue: "data",intValue: nil
那很棒,因为我要做的就是在将其发送到try脚本之前检查一下?
解决方法
try
的重点是在出现问题时引发错误。通过使用try!
,您可以保证不会出现问题,并在错误的情况下要求程序崩溃。有一个问题,所以程序崩溃了。
由于总是可以从服务器获取错误数据,因此永远不要在结果上使用try!
。使用do / catch处理错误。
URLSession.shared.dataTask(with: urls) { ( data,_,_) in
if let data = data {
do {
let podcast = try JSONDecoder().decode(Nowplayng.self,from: data)
if let track = podcast.data.first?.track {
DispatchQueue.main.async {
completion(track)
}
}
// But what do you want to do if there isn't a track here? (see below)
} catch {
// here,you need to deal with the error. At a minimum you need to
// log it. But you likely need to modify your completion handler to
// accept a Result or other way of passing errors back.
}
}
// And here,too. What if there's a web server error response? (see above)
}
这里没有简单的答案;这取决于您想要的行为。但是,一个不错的起点是将completion
函数更改为接受Result<Track,Error>
而不是仅接受Track。这样,您既可以传递失败,也可以传递成功。