Search code examples
swiftspotifyaccess-tokenoption-type

Spotify Renew Session Fatal error: unexpectedly found nil while unwrapping an Optional value


Attempting to renew session from Spotify so I can retrieve new access and refresh token. Starting on the first print line, I receive the fatal error.

@IBAction func renewSession(sender: AnyObject) {

    let auth = SPTAuth.defaultInstance()
    auth.tokenRefreshURL = NSURL(string: tokenRefresh)
    auth.tokenSwapURL = NSURL(string: tokenSwap)
    auth.session = self.spotifySession
    auth.sessionUserDefaultsKey = sessionKey

    if (auth.session != nil) {

        SPTAuth.defaultInstance().renewSession(SPTAuth.defaultInstance().session, callback: {(error, session) -> Void in

            if error != nil {

                print("The renewed Spotify session is", session)
                print("The renewed canonical user name in the session is", session.canonicalUsername)
                print("The renewed access Spotify token in session is - %@", auth.session.accessToken)
                print("The renewed encrypted refresh Spotify token in session is - %@", auth.session.encryptedRefreshToken)
                print("The renewed expiration date of the Spotify access token is - %@", auth.session.expirationDate)

            } else {

                print ("The problem with the renewal session is", error)

            }

        })

    }

Solution

  • You should be checking if session != nil, not if error != nil. There is some error but your code is moving control to the incorrect flow.