从Itunes API展开JSON - IOS App

时间:2017-11-14 21:01:37

标签: json swift parsing itunes

我的程序有问题。如果有人可以提供帮助,我将不胜感激。我已经尝试了几周来解析从iTunes API获取的JSON文件 (itunes.apple.com/search?term=song+you+want+to+search&entity=songTrack)。

但是,我的答案永远不会显示在我的桌面视图上,并且终端中会出现错误:

"2017-11-14 17:25:28.809190+0100 Itunes Learning[32409:6240818] [MC] Lazy loading NSBundle MobileCoreServices.framework
2017-11-14 17:25:28.810264+0100 Itunes Learning[32409:6240818] [MC] Loaded MobileCoreServices.framework
2017-11-14 17:25:28.823734+0100 Itunes Learning[32409:6240818] [MC] System group container for systemgroup.com.apple.configurationprofiles path is /Users/cyprianzander/Library/Developer/CoreSimulator/Devices/D52FD9D5-B6E4-4CE0-99E4-6E0EE15A680D/data/Containers/Shared/SystemGroup/systemgroup.com.apple.configurationprofiles
Could not cast value of type '__NSDictionaryI' (0x103b911d8) to 'NSArray' (0x103b90d28).
2017-11-14 17:25:29.875534+0100 Itunes Learning[32409:6240900] Could not cast value of type '__NSDictionaryI' (0x103b911d8) to 'NSArray' (0x103b90d28).
(lldb) "

这与JSON文件的设置大致相同:

  

{“resultCount”:50,“results”:[{“trackName”:“name”,“artistName”:“name2”},{“trackName”:“name3”,“artistName”:“name4”} ]}

(数组中的一个对象数组 - 意味着第一个对象位于远处的外部)。

我已尝试使用另一个API,我的功能确实有效。我觉得,为什么会发生这种情况的主要原因是因为iTunes API JSON文件非常复杂。它是数组中的各种非常长的对象,它位于较小的对象列表中。但是,另一个只是和对象数组。

这是我的代码:(我注意到在解析我需要的数据时会出现问题。我唯一需要知道的是如何正确解开我的JSON文件)

func parseData(searchTerm: String) {
    fetchedSong = []
    let itunesSearchTerm = searchTerm.replacingOccurrences(of: " ", with: "+", options: .caseInsensitive, range: nil)
    let escapedSearchTerm = itunesSearchTerm.addingPercentEncoding(withAllowedCharacters: [])!
    let urlString = "https://itunes.apple.com/search?term=\(escapedSearchTerm)&entity=song"
    let url = URL(string: urlString)!
    URLSession.shared.dataTask(with: url) { (data, response, error) in
        if let error = error {
            // If there is an error in the web request, print it to the console
            print(error)
            return
        }

        else {
            do {
                let fetchedData = try JSONSerialization.jsonObject(with: data!, options: .mutableLeaves) as! NSArray
                print(fetchedData)
                for eachFetchedSong in fetchedData {
                    let eachSong = eachFetchedSong as! [String: Any]
                    let song = eachSong["trackName"] as! String
                    let artist = eachSong["artistName"] as! String
                    self.fetchedSong.append(songs(song: song, artist : artist))

                }
                self.SongTableView.reloadData()

            }
            catch {
                print("An error occured while decoding the JSON object")
            }

        }
    }.resume()
}

如果有人能帮助我,我会非常高兴,特别是因为我已经坚持了三个星期,不断尝试不同的技术(这个似乎是最成功的)。

1 个答案:

答案 0 :(得分:3)

您的JSON数据不是数组。它是一个包含两个键/值对的字典。第一个是关键" resultCount"值为50,第二个是关键"结果"以数组作为其值。

永远不要用作!在解析JSON时,如果您收到意外结果,这将使您的应用程序崩溃。除非你能向我们解释它的作用以及你需要它的原因,否则不要使用.mutableLeaves。不要在你的Swift代码中使用NSArray。

处理一个错误并崩溃其他错误是没有意义的。我写了

if let fetchedDict = try? JSONSerialization(...) as? [String:Any], 
   let fetchedArray = fetchedDict ["results"] as? [[String:Any]] {
    for dict in fetchedArray {
        if let song = dict ["trackName"] as? String, 
           let artist = dict ["artistName"] as? String {
           ...
        }
    }
}