Spotify iOS SDK Swift display all (!) playlists (20+)

前端 未结 1 1240
攒了一身酷
攒了一身酷 2021-01-23 05:59

I\'m able to get the first 20 playlists fairly easily in Swift.

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

        let playLi         


        
相关标签:
1条回答
  • 2021-01-23 06:17

    You can't do it using a while loop, because the network calls are asynchronous. You can recursively request for the next page instead, and reload the table every time a page returns in the completion handler.

    Assuming you have the following property

    var playlists = [SPTPartialPlaylist]()
    

    In your getPlaylists function, you could have something like this (the way you have it using Alamofire also works fine):

                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)
                        }
                    }
                })
    

    Where getNextPlaylistPage looks something like this:

    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)
                }
            }
        })
    }
    

    If you wanted to do this more in keeping with the method you have in your question, you could build getNextPlaylistPage using a combination of Alamofire and SPTListPage's createRequestForNextPageWithAccessToken function.

    (Note that SPTPlaylistList is a subclass of SPTListPage.)

    It's also been a few months since I updated my SpotifyMetadata framework, so some of the above may have changed slightly...but the general concept remains the same.

    0 讨论(0)
提交回复
热议问题