2016-02-29 43 views
13

我正在嘗試使用Spotify的SDK爲我的iOS應用程序設置登錄名。我有登錄工作,但只有沒有令牌。一旦我添加這兩行代碼:在Spotify iOS應用程序中設置令牌禁用登錄回調

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

登錄不起作用。這是我的登錄代碼。

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(application:UIApplication,openURL url:NSURL,sourceApplication:String?,annotation:AnyObject) - > Bool'get called? – Ramis

+0

您是否設置了URL類型:目標 - >信息 - > URL類型?如果現在你應該這樣做? – Ramis

+0

您是否使用spotify_token_swap.rb腳本生成後端文件(交換/刷新)? – Ramis

回答

1

我會recomed你嘗試幾件事情:

  1. 能否請您發佈的內容是在你的URL類型標識符URL方案
  2. 我不知道它是否重要,但在我的情況下重定向URIURL Schemes是一樣的。我的應用程序下的重定向URI可以是found here
  3. 嘗試編寫使用URL Scheme打開您的應用程序的第二個應用程序。如果它不起作用,那麼這是URL模式中的問題。

由於代碼快照是在這裏:

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

當使用spotify_token_swap.rb文件生成的令牌文件,您將需要爲此設置正確的值:

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

我的重定向URI和URL方案是相同的。當我拿出上面寫的設置令牌刷新URL的兩行時,登錄工作正常,並調用openURL。 – PoKoBros

+0

你使用Spotify和Swift登錄成功了嗎? – PoKoBros

+0

我確實使用了objective-c來整合Spotify,但我不認爲這是一個問題。 – Ramis

2

我想你的後端(交換/刷新)服務器設置不正確,因爲不工作的服務器將導致登錄失敗。

我推薦this repository,你可以在heroku上設置一個簡單的服務器。

+0

這是否仍然適合你?我試圖設置它非常糟糕,但沒有機會 –

+0

是的,它仍然爲我工作。我重建了我的舊obj-c項目。 –

+0

垃圾...我的代碼是完美的...但我的Heroku服務器與這個紅寶石腳本給出:http://stackoverflow.com/questions/40813928/how-to-properly-handle-token-refresh-with-spotify- SDK和 - 迅速-3-錯誤碼38 –

相關問題