Spotify iOS SDK Swift显示所有(!)播放列表(20+)

时间:2017-05-25 14:25:19

标签: ios swift sdk spotify

我能够在Swift中轻松获得前20个播放列表。

func getPlaylists() {
    //DispatchQueue.global(qos: .userInitiated).async {

        let playListRequest = try! SPTPlaylistList.createRequestForGettingPlaylists(forUser: session.canonicalUsername, withAccessToken: session.accessToken)

        Alamofire.request(playListRequest)
            .response { response in


                let list = try! SPTPlaylistList(from: response.data, with: response.response)

                for playList in list.items  {
                    if let playlist = playList as? SPTPartialPlaylist {


                        let currentPlaylist: PlaylistItem = PlaylistItem(playlistName: playlist.name, playlistURL: playlist.uri.absoluteString)
                        self.playlists.append(currentPlaylist)
                    }
                }
                self.tableView.reloadData()
        }

到目前为止 - 太好了。但是这(根据文档仅提供前20个播放列表。

如何通过添加嵌套的循环来获得更多(全部!)播放列表

 while list.hasNextPage == true {
}

重构C代码不成功

提前致谢!

1 个答案:

答案 0 :(得分:2)

您无法使用while循环执行此操作,因为网络调用是异步的。您可以递归地请求下一页,并在每次页面在完成处理程序中返回时重新加载表。

假设您有以下属性

var playlists = [SPTPartialPlaylist]()

在你的getPlaylists功能中,你可以拥有这样的东西(使用Alamofire的方式也可以正常工作):

            SPTPlaylistList.playlists(forUser: session.canonicalUsername, withAccessToken: session.accessToken, callback: { (error, response) in
                self.activityIndicator.stopAnimating()
                if let listPage = response as? SPTPlaylistList, let playlists = listPage.items as? [SPTPartialPlaylist] {
                    self.playlists = playlists    // or however you want to parse these
                    self.tableView.reloadData()
                    if listPage.hasNextPage {
                        self.getNextPlaylistPage(currentPage: listPage)
                    }
                }
            })

getNextPlaylistPage看起来像这样:

func getNextPlaylistPage(currentPage: SPTListPage) {
    currentPage.requestNextPage(withAccessToken: AppDelegate.shared().auth?.session.accessToken, callback: { (error, response) in
        if let page = response as? SPTListPage, let playlists = page.items as? [SPTPartialPlaylist] {
            self.playlists.append(contentsOf: playlists)     // or parse these beforehand, if you need/want to
            self.tableView.reloadData()
            if page.hasNextPage {
                self.getNextPlaylistPage(currentPage: page)
            }
        }
    })
}

如果您希望更多地按照问题中的方法执行此操作,则可以使用Alamofire和getNextPlaylistPage SPTListPage的组合构建createRequestForNextPageWithAccessToken功能

(请注意SPTPlaylistListSPTListPage的子类。)

自从我更新了我的SpotifyMetadata框架以来,这也是几个月,所以上面的一些可能会略有改变......但是一般概念保持不变。