无法遍历SPTPlaylistList项

时间:2018-06-08 02:27:04

标签: swift sdk spotify

我正在尝试访问Spotify用户的所有播放列表

 let request2: URLRequest = try! SPTPlaylistList.createRequestForGettingPlaylists(forUser: self.username, withAccessToken: accessToken)
    print(request2)
    SPTRequest.sharedHandler().perform(request2) { (error, response, data) in
        if error == nil {
            print(response)
            let playlists = try! SPTPlaylistList(from: data, with: response)
}else{
            print(error)
        }
    }

如果我打印'播放列表',我可以看到播放列表

some([<SPTPartialPlaylist: 0x10aa854d0>: john mayer [2 tracks] (spotify:user:virajdeshpande88:playlist:3BLBrqb3CURu5KFPqdYqd1), <SPTPartialPlaylist: 0x10aa922a0>: beatles [2 tracks] (spotify:user:virajdeshpande88:playlist:2t6z8KEhZGzY7Tqvy8QoW4)])

但我无法单独访问播放列表或遍历播放列表.items。如果我执行以下操作:

print (playlists.items[0])

我得到'在打开一个Optional值时意外发现nil'。

更新:我尝试使用playlistsForUser:withAccessToken:callback:我现在可以访问所有用户的播放列表了。但是,如果下面的代码块在我上面发布的代码段的if {}块内,它似乎才有效。如果这个块只是单独放置,我再次得到nil值错误。

    SPTPlaylistList.playlists(forUser: self.username, withAccessToken: accessToken, callback: {(error, playlist_list)  in
    if error == nil {
        let list = playlist_list as! SPTPlaylistList
        print(list.items[0])
        print(list.items[1])
        let playlist = list.items[0] as! SPTPartialPlaylist
        print(playlist.name)
    }else{
        print("latest error")
       }
})

1 个答案:

答案 0 :(得分:0)

您应该避免使用强制解包!

    if let request2: URLRequest = try? SPTPlaylistList.createRequestForGettingPlaylists(forUser: self.username, withAccessToken: accessToken){
        print(request2)
        SPTRequest.sharedHandler().perform(request2) { (error, response, data) in
            if error == nil {
                print(response)
                if let playlists = try? SPTPlaylistList(from: data, with: response) {
                    playlists.forEach{ playlist in
                        print(playlist)
                        // do thing with your each playlist
                    }
                }
            }else{
                print(error)
            }
        }
    }