在 Swift 3.0 中访问从 iTunes API 解析的 JSON 对象

Posted

技术标签:

【中文标题】在 Swift 3.0 中访问从 iTunes API 解析的 JSON 对象【英文标题】:Accessing JSON Objects parsed from iTunes API in Swift 3.0 【发布时间】:2016-10-20 23:38:22 【问题描述】:

我正在尝试使用 Swift 3.0 从 iTunes API 访问以 JSON 格式解析的项目,但在解析对象后我很难访问它们。正在以这种格式解析对象:


resultCount = 50;
results =     (
            
        artistId = 70936;
        artistName = "Johnny Cash";
        artistViewUrl = "https://itunes.apple.com/us/artist/johnny-cash/id70936?uo=4";
        artworkUrl100 = "http://is2.mzstatic.com/image/thumb/Music3/v4/13/ae/73/13ae735e-33d0-1480-f51b-4150d4a45696/source/100x100bb.jpg";
        artworkUrl30 = "http://is2.mzstatic.com/image/thumb/Music3/v4/13/ae/73/13ae735e-33d0-1480-f51b-4150d4a45696/source/30x30bb.jpg";
        artworkUrl60 = "http://is2.mzstatic.com/image/thumb/Music3/v4/13/ae/73/13ae735e-33d0-1480-f51b-4150d4a45696/source/60x60bb.jpg";
        collectionCensoredName = "The Essential Johnny Cash";
        collectionExplicitness = notExplicit;
        collectionId = 251001680;
        collectionName = "The Essential Johnny Cash";
        collectionPrice = "14.99";
        collectionViewUrl = "https://itunes.apple.com/us/album/ring-of-fire/id251001680?i=251002253&uo=4";
        country = USA;
        currency = USD;
        discCount = 2;
        discNumber = 1;
        isStreamable = 1;
        kind = song;
        previewUrl = "http://a1144.phobos.apple.com/us/r1000/070/Music/b3/99/be/mzi.qvkhtgfg.aac.p.m4a";
        primaryGenreName = Country;
        releaseDate = "2002-02-12T08:00:00Z";
        trackCensoredName = "Ring of Fire";
        trackCount = 18;
        trackExplicitness = notExplicit;
        trackId = 251002253;
        trackName = "Ring of Fire";
        trackNumber = 15;
        trackPrice = "1.29";
        trackTimeMillis = 155707;
        trackViewUrl = "https://itunes.apple.com/us/album/ring-of-fire/id251001680?i=251002253&uo=4";
        wrapperType = track;
    ,

我希望能够访问所有 50 个结果中的信息,例如艺术家姓名。这是我试图获取艺术家名称并将其添加到我的 NSDictionary 的解析函数,但它不断返回它无法解开字典。

func parser() 
    let enteredText:String = (tbxSearch.text?.replacingOccurrences(of: " ", with: "+"))!
    let url = "https://itunes.apple.com/search?term=\(enteredText)"
    print(url)
    guard let urlRequest = URL(string: url) else
    
        print("Error creating endpoint")
        return
    
    let request = URLRequest(url: urlRequest)
    URLSession.shared.dataTask(with: request) (data,response,error) in
        do
        
            guard let data = data else
            
                return
            
            guard let json = try JSONSerialization.jsonObject(with: data, options: []) as? NSDictionary else
            
                return
            
            if let results = json["results"] as? NSDictionary
            
                self.avObjects.avDict.setValue("Artist Name", forKey: results["artistName"] as! String)
                print(self.avObjects.avDict)
            
            else  
              
                print("Couldn't unwrap the dictionary.")
            
            print(json)
        
        catch let error as NSError
        
            print(error.debugDescription)
        
    .resume()

【问题讨论】:

【参考方案1】:

看起来results 是一个字典数组,而不仅仅是字典。

而不是这个:if let results = json["results"] as? NSDictionary

试试这个:if let results = json["results"] as? NSArray

然后,您可以映射或迭代数组中的每个元素,例如从每个元素中提取 "artistName"

【讨论】:

【参考方案2】:

results 是一个字典数组,而不是字典本身。尝试改变这个:

if let results = json["results"] as? NSDictionary

到:

if let results = json["results"] as? NSArray

然后迭代结果。结果的每个元素都是一个字典,带有artistName等属性。

【讨论】:

执行此操作后,当我尝试为字典设置值时,我收到一条错误消息,指出它无法将 String 类型的值转换为预期的参数类型 Int

以上是关于在 Swift 3.0 中访问从 iTunes API 解析的 JSON 对象的主要内容,如果未能解决你的问题,请参考以下文章

内购 - 斯威夫特 3.0

iOS + Swift,如何访问所有音乐文件 [关闭]

iOS 10 / Swift 3.0 / XCode 8 总结

如何在swift 3.0中计算用户从当前位置行进的距离

Swift 3.0 无法从 UITableView 中删除一行

无法从同一类中的闭包中更改变量 [swift 3.0]