JSON返回null-导致应用崩溃首先检查数据

问题描述

所以我想知道在将返回数据发送到以下命令之前如何检查返回数据是否包含标题。

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。这样,您既可以传递失败,也可以传递成功。

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...