2016-02-29 14 views
13

Sto tentando di configurare l'accesso per la mia app iOS utilizzando l'SDK di Spotify. Ho il login funzionante, ma solo senza token. Una volta aggiungo queste due righe di codice:L'impostazione dei token nell'app iOS di Spotify disabilita la richiamata di login

SPTAuth.defaultInstance().tokenSwapURL = NSURL(string: kTokenSwapURL) 
SPTAuth.defaultInstance().tokenRefreshURL = NSURL(string: kTokenRefreshServiceURL) 

Il login non funziona. Questo è il mio codice per il login.

AppDelegate.swift

let kClientID = "my-client-id" 
let kCallbackURL = "my-callback-url" 
let kTokenSwapURL = "my-token-swap-url" 
let kTokenRefreshServiceURL = "my-token-refresh-url" 

func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool { 
    // Override point for customization after application launch. 

    // Override point for customization after application launch. 
    SPTAuth.defaultInstance().clientID = kClientID 
    SPTAuth.defaultInstance().redirectURL = NSURL(string: kCallbackURL) 
    SPTAuth.defaultInstance().requestedScopes = [SPTAuthStreamingScope, SPTAuthUserReadPrivateScope, SPTAuthPlaylistReadPrivateScope] 
    SPTAuth.defaultInstance().sessionUserDefaultsKey = "SpotifySession" 

    window = UIWindow(frame: UIScreen.mainScreen().bounds) 

    let loginViewController = LoginViewController(nibName: "LogInViewController", bundle: nil) 
    let navigationController = UINavigationController(rootViewController: loginViewController) 

    window?.rootViewController = navigationController 
    window?.makeKeyAndVisible() 

    return true 
} 

func application(application: UIApplication, openURL url: NSURL, sourceApplication: String?, annotation: AnyObject) -> Bool { 
    let authCallback : SPTAuthCallback = { error, session in 
     // This is the callback that'll be triggered when auth is completed (or fails). 

     if (error != nil) { 
      print(error); 
      return; 
     } 

     let userDefaults = NSUserDefaults.standardUserDefaults() 
     let sessionData = NSKeyedArchiver.archivedDataWithRootObject(session) 
     userDefaults.setObject(sessionData, forKey: SPTAuth.defaultInstance().sessionUserDefaultsKey) 
     userDefaults.synchronize() 

     AuthHandler.sharedHandler.loginWithSession(session) 
    }; 

    if SPTAuth.defaultInstance().canHandleURL(url) { 
     SPTAuth.defaultInstance().handleAuthCallbackWithTriggeredAuthURL(url, callback:authCallback) 
     return true 
    } 

    return false; 
} 

LoginViewController.swift

class LoginViewController: UIViewController { 

    let kClientID = "my-client-id" 
    let kCallbackURL = "my-callback-url" 
    let kTokenSwapURL = "my-token-swap-url" 
    let kTokenRefreshServiceURL = "my-token-refresh-url" 


    var session: SPTSession! 

    var logIn: UIButton! 

    var auth : SPTAuthViewController? 

    override func viewWillAppear(animated: Bool) { 
     // set login callback for what happens when session is got 
     AuthHandler.sharedHandler.setLoginCallback({ success in 
      if (success) { 
       self.transitionToPlaylistScreen() 
      } 
     }) 

     // if session is still valid, login 
     let userDefaults = NSUserDefaults.standardUserDefaults() 

     if let sessionObj:AnyObject = userDefaults.objectForKey("SpotifySession") { // session available 
      let sessionDataObj = sessionObj as! NSData 

      let session = NSKeyedUnarchiver.unarchiveObjectWithData(sessionDataObj) as! SPTSession 

      if !session.isValid() { 
       SPTAuth.defaultInstance().renewSession(session, callback: { (error:NSError!, renewdSession:SPTSession!) -> Void in 
        if error == nil { 
         let sessionData = NSKeyedArchiver.archivedDataWithRootObject(session) 
         userDefaults.setObject(sessionData, forKey: SPTAuth.defaultInstance().sessionUserDefaultsKey) 
         userDefaults.synchronize() 

         self.session = renewdSession 
         AuthHandler.sharedHandler.loginWithSession(self.session!) 
        } else { 
         print(error.localizedDescription) 
        } 
       }) 
      } else { 
       self.session = session 
       AuthHandler.sharedHandler.loginWithSession(self.session!) 
      } 
     } 
    } 

    override func viewDidLoad() { 
     // add observer for login success 
     NSNotificationCenter.defaultCenter().addObserver(self, selector: Selector("transitionToPlaylistScreen"), name: "loginSuccess", object: nil) 

     // code to set up the login button 
    } 

    func transitionToPlaylistScreen() { 
     if (self.auth != nil) { 
      self.dismissViewControllerAnimated(true, completion: nil) 
      self.auth = nil 
     } 
     let playlistScreen = PlaylistViewController() 
     let navigation = UINavigationController(rootViewController: playlistScreen) 
     dispatch_async(dispatch_get_main_queue(), { 
      self.presentViewController(navigation, animated: true, completion: nil) 
     }) 
    } 

    func loginToSpotify() { 
     // if session isn't valid, login within app 
     dispatch_async(dispatch_get_main_queue(), { 
      self.auth = SPTAuthViewController.authenticationViewController() 
      self.auth?.delegate = AuthHandler.sharedHandler 
      self.auth!.modalPresentationStyle = .OverCurrentContext 
      self.auth!.modalTransitionStyle = .CrossDissolve 
      self.modalPresentationStyle = .CurrentContext 
      self.definesPresentationContext = true 
      self.auth!.clearCookies({ 
       dispatch_async(dispatch_get_main_queue(), { 
        self.presentViewController(self.auth!, animated: false, completion: nil) 
       }) 
      }) 
     }) 
    } 
} 

AuthHandler.swift

class AuthHandler: NSObject, SPTAuthViewDelegate { 
    static let sharedHandler = AuthHandler() 

    var session: SPTSession? 

    var callback: (Bool -> Void)? 

    func setLoginCallback(callback: (Bool -> Void)) { 
     self.callback = callback 
    } 

    func authenticationViewController(authenticationViewController: SPTAuthViewController!, didFailToLogin error: NSError!) { 
     if let function = callback { 
      function(false) 
     } 
    } 

    func authenticationViewController(authenticationViewController: SPTAuthViewController!, didLoginWithSession session: SPTSession!) { 
     self.loginWithSession(session) 
    } 

    func authenticationViewControllerDidCancelLogin(authenticationViewController: SPTAuthViewController!) { 
     if let function = callback { 
      function(false) 
     } 
    } 

    func loginWithSession(session: SPTSession) { 
     self.session = session 
     SPTAuth.defaultInstance().session = session 
     if let function = callback { 
      function(true) 
     } 
    } 
} 
+0

È func 'application (applicazione: UIApplicazione, URL openURL: NSURL, sourceApplication: String ?, annotazione: AnyObject) -> Bool' get call? – Ramis

+0

Hai impostato il tipo di URL in: TARGET -> Info -> Tipi di URL? Se ora dovresti farlo? – Ramis

+0

Hai generato file di backend (scambia/aggiorna) usando lo script spotify_token_swap.rb? – Ramis

risposta

1

Quello che vorrei consiglio a provare diverse cose:

  1. La prego di inviare ciò che è in vostro Tipi URL Identifier e URL Schemes?
  2. Non so è importante, ma nel mio caso Uir reindirizzamento e Schemi URL è lo stesso. L'URI di reindirizzamento può essere found here in Le mie applicazioni.
  3. Prova a scrivere la seconda app che sta aprendo la tua app utilizzando lo schema URL. Se non funziona, ecco il problema negli schemi URL.

Come codice di snapshot è qui:

let kCallbackURL = "myWhosampled://" 
let url = NSURL(string: kCallbackURL) 
UIApplication.sharedApplication().openURL(url!) 

Durante la generazione di file per i token utilizzando spotify_token_swap.rb file che si avrebbe bisogno di impostare valori corretti per questo:

CLIENT_ID = "e6695c6d22214e0f832006889566df9c" 
CLIENT_SECRET = "29eb02041ba646179a1189dccac112c7" 
ENCRYPTION_SECRET = "cFJLyifeUJUBFWdHzVbykfDmPHtLKLGzViHW9aHGmyTLD8hGXC" 
CLIENT_CALLBACK_URL = "spotifyiossdkexample://" 
AUTH_HEADER = "Basic " + Base64.strict_encode64(CLIENT_ID + ":" + CLIENT_SECRET) 
SPOTIFY_ACCOUNTS_ENDPOINT = URI.parse("https://accounts.spotify.com") 

set :port, 1234 # The port to bind to. 
set :bind, '0.0.0.0' # IP address of the interface to listen on (all) 
+0

Il mio reindirizzamento URI e gli schemi URL sono gli stessi. Quando tolgo le due righe che ho scritto sopra impostando l'URL di aggiornamento del token, l'accesso funziona correttamente e si chiama openURL. – PoKoBros

+0

hai avuto successo con l'accesso con Spotify e Swift ?? – PoKoBros

+0

Ho usato l'obiettivo-c per integrare Spotify, ma non penso che questo sia un problema. – Ramis

2

Immagino che il tuo server back-end (swap/refresh) non sia impostato correttamente, perché un server non funzionante causa il log in per fallire.

Raccomando this repository, che è possibile impostare un server semplice su heroku.

+0

funziona ancora per te? ho provato a configurarlo così male, ma nessuna possibilità –

+0

Sì, funziona ancora per me. Ho ricostruito il mio vecchio progetto obj-c. –

+0

crap ... il mio codice è perfetto ... ma il mio server heroku con questo script ruby ​​offre: http://stackoverflow.com/questions/40813928/how-to-properly-handle-token-refresh-with-spotify- sdk-e-swift-3-error-code-38 –

Problemi correlati