Неправильный трек Spotify - PullRequest
3 голосов
/ 10 июля 2019

Я использую iOS SDK. У меня есть две кнопки для воспроизведения песен

Один для трека Кэти Перри Фейерверк

appRemote.playerAPI?.play("spotify:track:4lCv7b86sLynZbXhfScfm2") { (restult, error) in }

Второй для трека Робби Уильямса Angles

appRemote.playerAPI?.play("spotify:track:1M2nd8jNUkkwrc1dgBPTJz") { (restult, error) in }

Я переключаюсь между ними, и он работает правильно.

Но если, например, трек Робби Уильямса заканчивается, чем воспроизводится новая песня, например песня Снуп Дога. Я переключаюсь на Кэти, слушаю ее песню до конца, начинается новая песня, например, песня Metallica. Теперь, когда я пытаюсь переключиться между Кэти и Робби, я переключаюсь между Metallica и Snoop Dog. Что я сделал не так?

Я пытался: appRemote.playerAPI?.setRepeatMode(.track) { (restult, error) in }, но это не помогает.

Полный источник:


let SpotifyClientID = "xxx"
let SpotifyRedirectURL = URL(string: "xxx://callback")!

class SpotifyManager: NSObject {
    static var shared = SpotifyManager()

    static var playerStateDidChange: (()->())?

    static var configuration = SPTConfiguration(
        clientID: SpotifyClientID,
        redirectURL: SpotifyRedirectURL
    )

    static var sessionManager: SPTSessionManager = {
        if let tokenSwapURL = URL(string: "https://xxx.glitch.me/api/token"),
            let tokenRefreshURL = URL(string: "https://xxx.glitch.me/api/refresh_token") {
            configuration.tokenSwapURL = tokenSwapURL
            configuration.tokenRefreshURL = tokenRefreshURL
        }

        if currentTrackId.count != 0 {
            configuration.playURI = "spotify:track:\(SpotifyManager.currentTrackId)"
        } else {
            configuration.playURI = ""
        }

        let manager = SPTSessionManager(configuration: configuration, delegate: shared)
        return manager
    }()

    static var appRemote: SPTAppRemote = {
        let appRemote = SPTAppRemote(configuration: configuration, logLevel: .debug)
        appRemote.delegate = shared
        return appRemote
    }()

    static var currentTrackId = ""

    static func play(track_id: String) {
        currentTrackId = track_id
        SpotifyManager.playerStateDidChange?()
        if sessionManager.session == nil || appRemote.isConnected == false {
            let requestedScopes: SPTScope = [.appRemoteControl]
            if #available(iOS 11.0, *) {
                sessionManager.initiateSession(with: requestedScopes, options: .default)
            }
        } else {
            appRemote.playerAPI?.play("spotify:track:\(track_id)") { (restult, error) in
            }
        }
    }
    static func pause() {
        currentTrackId = ""
        SpotifyManager.playerStateDidChange?()
        appRemote.playerAPI?.pause { (restult, error) in

        }
    }
    static func isPlaying(track_id: String) -> Bool {
        return SpotifyManager.currentTrackId == track_id
    }
}

extension SpotifyManager: SPTSessionManagerDelegate {
    func sessionManager(manager: SPTSessionManager, didInitiate session: SPTSession) {
        NSLog("didInitiate \(session)")

        SpotifyManager.appRemote.connectionParameters.accessToken = session.accessToken
        SpotifyManager.appRemote.connect()
    }
    func sessionManager(manager: SPTSessionManager, didFailWith error: Error) {
        NSLog("didFailWith \(error)")
    }
    func sessionManager(manager: SPTSessionManager, didRenew session: SPTSession) {
        NSLog("didRenew \(session)")
    }
}

extension SpotifyManager: SPTAppRemoteDelegate, SPTAppRemotePlayerStateDelegate {
    func appRemoteDidEstablishConnection(_ appRemote: SPTAppRemote) {
        NSLog("didEstablishConnection")
        SpotifyManager.appRemote.playerAPI?.delegate = self
        SpotifyManager.appRemote.playerAPI?.subscribe { (result, error) in
            if let error = error {
                NSLog(error.localizedDescription)
            }
        }
        SpotifyManager.playerStateDidChange?()
    }
    func appRemote(_ appRemote: SPTAppRemote, didDisconnectWithError error: Error?) {
        NSLog("didDisconnectWithError")
        SpotifyManager.currentTrackId = ""
        SpotifyManager.appRemote.disconnect()
        SpotifyManager.playerStateDidChange?()
    }
    func appRemote(_ appRemote: SPTAppRemote, didFailConnectionAttemptWithError error: Error?) {
        NSLog("didFailConnectionAttemptWithError")
        SpotifyManager.currentTrackId = ""
        SpotifyManager.appRemote.disconnect()
        SpotifyManager.playerStateDidChange?()
    }
    func playerStateDidChange(_ playerState: SPTAppRemotePlayerState) {
        NSLog("\(playerState.track.name)")
        SpotifyManager.playerStateDidChange?()
    }
}


...