SPTSessionManager не инициализируется и не дает сбой - PullRequest
0 голосов
/ 10 ноября 2019

Когда я пытаюсь вызвать sessionManager.initialize(), ни func sessionManager(manager: SPTSessionManager, didFailWith error: Error), ни func sessionManager(manager: SPTSessionManager, didInitiate session: SPTSession) не вызываются.

У меня есть сервер nodeJS, работающий на AWS для доступа к токену и обновления, и я также попытался запустить локальный Rubyсервер для получения токена. Независимо от того, что звонить initialize() ничего не делает. Это терпит неудачу или успешно, и ничто не выводится на консоль. Я попытался запустить отладчик XCode, и кажется, что программа просто пропускает initialize. Вот мой полный файл ViewController.swift с удаленными несвязанными / частными частями:

import UIKit
import Firebase

class LobbyAdminViewController: UIViewController, SPTSessionManagerDelegate, SPTAppRemoteDelegate, SPTAppRemotePlayerStateDelegate  {
    fileprivate let SpotifyClientID = "client_id"
    fileprivate let SpotifyRedirectURI = URL(string: "redirect_url")!
    fileprivate var lastPlayerState: SPTAppRemotePlayerState?
    var refreshAPI = "token_server/refresh_token"
    var tokenAPI = "token_server/token"

    lazy var configuration: SPTConfiguration = {
           let configuration = SPTConfiguration(clientID: SpotifyClientID, redirectURL: SpotifyRedirectURI)
           configuration.playURI = ""
           configuration.tokenSwapURL = URL(string: tokenAPI)
           configuration.tokenRefreshURL = URL(string: refreshAPI)
           return configuration
       }()

       lazy var sessionManager: SPTSessionManager = {
           let manager = SPTSessionManager(configuration: configuration, delegate: self)
           return manager
       }()

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

    override func viewDidLoad() {
        super.viewDidLoad()
        let random = Int(arc4random_uniform(900000) + 100000)
        lobbyCode = String(random)
        lobbyCodeLabel.text = lobbyCode
        var ref: DatabaseReference!
        ref = Database.database().reference()
        ref.child(lobbyCode).child("null").setValue("null")
        let scope: SPTScope = [.appRemoteControl]
        if #available(iOS 11, *) {
            print("ios 11+")
            sessionManager.initiateSession(with: scope, options: .clientOnly)
        } else {
            print("ios 11-")
            sessionManager.initiateSession(with: scope, options: .clientOnly, presenting: self)
        }
    }

    func update(playerState: SPTAppRemotePlayerState) {
        print("Updating")
        lastPlayerState = playerState
        currentSongLabel.text = playerState.track.name
        currentArtistLabel.text = playerState.track.artist.name
        if playerState.isPaused {
            pausePlayButton.setBackgroundImage(UIImage(named: "play"), for: .normal)
        } else {
            pausePlayButton.setBackgroundImage(UIImage(named: "pause"), for: .normal)
        }
    }

    func fetchPlayerState() {
        print("Getting player state")
        appRemote.playerAPI?.getPlayerState({ [weak self] (playerState, error) in
            if let error = error {
                print("Error getting player state:" + error.localizedDescription)
            } else if let playerState = playerState as? SPTAppRemotePlayerState {
                self?.update(playerState: playerState)
            }
        })
    }

    @IBAction func onTap_pausePlayButton(_ sender: UIButton) {
        print("tapped")
        if let lastPlayerState = lastPlayerState, lastPlayerState.isPaused {
            appRemote.playerAPI?.resume(nil)
            print("Resuming")
        } else {
            appRemote.playerAPI?.pause(nil)
            print("Pausing")
        }
    }

    func sessionManager(manager: SPTSessionManager, didFailWith error: Error) {
        print("Bad init")
        print(error.localizedDescription)
    }

    func sessionManager(manager: SPTSessionManager, didRenew session: SPTSession) {
        print("Renewed")
    }

    func sessionManager(manager: SPTSessionManager, didInitiate session: SPTSession) {
        print("Trying to connect")
        appRemote.connectionParameters.accessToken = session.accessToken
        print(session.accessToken)
        appRemote.connect()
    }

    // MARK: - SPTAppRemoteDelegate

    func appRemoteDidEstablishConnection(_ appRemote: SPTAppRemote) {
        print("App Remote Connected")
        appRemote.playerAPI?.delegate = self
        appRemote.playerAPI?.subscribe(toPlayerState: { (success, error) in
            if let error = error {
                print("Error subscribing to player state:" + error.localizedDescription)
            }
        })
        fetchPlayerState()
    }

    func appRemote(_ appRemote: SPTAppRemote, didDisconnectWithError error: Error?) {
        lastPlayerState = nil
        print("Error connecting to app remote")
    }

    func appRemote(_ appRemote: SPTAppRemote, didFailConnectionAttemptWithError error: Error?) {
        lastPlayerState = nil
        print("Another error connectiong to app remote")
    }

    // MARK: - SPTAppRemotePlayerAPIDelegate

    func playerStateDidChange(_ playerState: SPTAppRemotePlayerState) {
        print("Player state changed")
        update(playerState: playerState)
    }

    // MARK: - Private Helpers

    fileprivate func presentAlertController(title: String, message: String, buttonTitle: String) {
        let controller = UIAlertController(title: title, message: message, preferredStyle: .alert)
        let action = UIAlertAction(title: buttonTitle, style: .default, handler: nil)
        controller.addAction(action)
        present(controller, animated: true)
    }

}

Единственное print() утверждение, которое запускается, это "ios 11" в viewDidLoad() Я искал в интернете всех, у кого естьта же проблема и всплыла пустая. Единственное, о чем я могу думать, это может вызвать эту проблему - это известная проблема во время выполнения с iOS 13. Эта ошибка:

Can't end BackgroundTask: no background task exists with identifier 8 (0x8), or it may have already been ended. Break in UIApplicationEndBackgroundTaskError() to debug.

срабатывает каждый раз, когда приложение отправляется в фоновый режим(т. е. когда приложение перенаправляет в spotify для аутентификации). Однако эта проблема существует даже с пустым приложением в XCode и не останавливает выполнение.

...