简体   繁体   中英

Spotify SDK player not working: Error Domain=com.spotify.ios-sdk.playback Code=1 “The operation failed due to an unspecified issue.”

I am currently developing an iOS app to login to my Spotify account and play songs in there.

This is my code:

import UIKit
import AVKit

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate, 
SPTAudioStreamingDelegate {

var window: UIWindow?

let kClientId = "hidden------my client ID"
let kRedirectUrl = URL(string: "spotify-study2-login://return-after-login")

var session: SPTSession?
var player: SPTAudioStreamingController?

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey : Any]? = nil) -> Bool {

    // set up Spotofy
    SPTAuth.defaultInstance().clientID = kClientId
    SPTAuth.defaultInstance().redirectURL = kRedirectUrl
    SPTAuth.defaultInstance().requestedScopes = [SPTAuthStreamingScope] as [AnyObject]
    let loginUrl = SPTAuth.defaultInstance().spotifyAppAuthenticationURL()
    application.open(loginUrl!)

    return true
}

// handle auth
func application(_ application: UIApplication, open url: URL, sourceApplication: String?, annotation: Any) -> Bool {

    if SPTAuth.defaultInstance().canHandle(url) {
        SPTAuth.defaultInstance().handleAuthCallback(withTriggeredAuthURL: url, callback: { error, session in
            if error != nil {
                print("*** Auth error: \(String(describing: error))")
            }
            // Call the -loginUsingSession: method to login SDK
            self.loginUsingSession(session: session!)
        })
        return true
    }

    return false
}

func loginUsingSession(session: SPTSession) {
   // Get the player Instance
    player = SPTAudioStreamingController.sharedInstance()
    if let player = player {
        player.delegate = self
        // start the player (will start a thread)
        try! player.start(withClientId: kClientId)
        // Login SDK before we can start playback
        player.login(withAccessToken: session.accessToken)

        let urlStr = "spotify:track:3yMPqvbPNaL5DUDOmwEr6l" // a song I choose. I already confirmed this song really exsits.
        self.player?.playSpotifyURI(urlStr, startingWith: 0, startingWithPosition: 0, callback: { error in
            if error != nil {
                print("*** failed to play: \(String(describing: error))")
                return
            } else {
                print("play")
            }
        })

    }
}

// MARK: SPTAudioStreamingDelegate.
func audioStreamingDidLogin(audioStreaming: SPTAudioStreamingController!) {

    let urlStr = "spotify:track:3yMPqvbPNaL5DUDOmwEr6l" // a song I choose. I already confirmed this song really exsits.
    player!.playSpotifyURI(urlStr, startingWith: 0, startingWithPosition: 0, callback: { error in
        if error != nil {
            print("*** failed to play: \(String(describing: error))")
            return
        } else {
            print("play")
        }
    })
}

func applicationWillResignActive(_ application: UIApplication) {
    // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
    // Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game.

    //log
    print("func applicationWillResignActive has been called")
}

func applicationDidEnterBackground(_ application: UIApplication) {
    // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
    // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.

    //log
    print("func applicationDidEnterBackground has been called")
}

func applicationWillEnterForeground(_ application: UIApplication) {
    // Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.

    //log
    print("func applicationWillEnterForeground has been called")
}

func applicationDidBecomeActive(_ application: UIApplication) {
    // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.

    //log
    print("applicationDidBecomeActive")

}

func applicationWillTerminate(_ application: UIApplication) {
    // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.

    //log
    print("func applicationWillTerminate has been called")
}
}

When I run the debugger, I found an error message saying:

Error Domain=com.spotify.ios-sdk.playback Code=1 "The operation failed due to an unspecified issue." UserInfo={NSLocalizedDescription=The operation failed due to an unspecified issue.}

This error message came from the part below:

// MARK: SPTAudioStreamingDelegate.
func audioStreamingDidLogin(audioStreaming: 
SPTAudioStreamingController!) {

    let urlStr = "spotify:track:3yMPqvbPNaL5DUDOmwEr6l" // a song I choose. I already confirmed this song really exsits.
    player!.playSpotifyURI(urlStr, startingWith: 0, startingWithPosition: 0, callback: { error in
        if error != nil {
            print("*** failed to play: \(String(describing: error))")
            return
        } else {
            print("play")
        }
    })
}

In addition, I also found

2017-11-19 19:31:04.050872+0900 SpotifyStudy2[756:110616] Caching allowed 1

from the part below:

// Login SDK before we can start playback
        player.login(withAccessToken: session.accessToken)

Googling about this problem cost me lots of time but still I haven't found a nice answer to solve this. If you have any idea what this error specifically means, your answer will help me so much...! Thank you in advance.

I was facing the same issue, and I have resolved using belove code

    do {
        try SPTAudioStreamingController.sharedInstance()?.start(withClientId: SPTAuth.defaultInstance().clientID, audioController: nil, allowCaching: true)
            SPTAudioStreamingController.sharedInstance().delegate = self
            SPTAudioStreamingController.sharedInstance().playbackDelegate = self
            SPTAudioStreamingController.sharedInstance().diskCache = SPTDiskCache() /* capacity: 1024 * 1024 * 64 */
            SPTAudioStreamingController.sharedInstance().login(withAccessToken: "Token here")
    } catch _ {
        print("catch")
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM