【问题标题】:Setting Auth Tokens in Spotify iOS SDK在 Spotify iOS SDK 中设置身份验证令牌
【发布时间】:2017-10-30 07:33:37
【问题描述】:

Spotify iOS SDK 全部在 Objective-c 中,截至今天,看起来任何使用 SDK 的请求都需要令牌。当我尝试搜索歌曲时,出现此错误:

["error": {
    message = "No token provided";
    status = 401;
}]

这是我的 appDelegate 代码:

var auth = SPTAuth()
var window: UIWindow?


func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
    //Neccessary Spotify stuff
    auth.redirectURL = URL(string: "my_redirect_url")
    auth.sessionUserDefaultsKey = "current session"

    FIRApp.configure()

    window = UIWindow(frame: UIScreen.main.bounds)
    window?.makeKeyAndVisible()
    window?.rootViewController = CustomTabBarController()

    return true
}

// 1
func application(_ application: UIApplication, open url: URL, sourceApplication: String?, annotation: Any) -> Bool {
    // 2- check if app can handle redirect URL
    if auth.canHandle(auth.redirectURL) {
        // 3 - handle callback in closure
        auth.handleAuthCallback(withTriggeredAuthURL: url, callback: { (error, session) in
            // 4- handle error
            if error != nil {
                print("error!")
            }
            // 5- Add session to User Defaults
            let userDefaults = UserDefaults.standard
            let sessionData = NSKeyedArchiver.archivedData(withRootObject: session as Any)
            userDefaults.set(sessionData, forKey: "SpotifySession")
            userDefaults.synchronize()
            // 6 - Tell notification center login is successful
            NotificationCenter.default.post(name: Notification.Name(rawValue: "loginSuccessfull"), object: nil)
        })
        return true
    }
    return false
}

如何在 Swift 中设置令牌?

【问题讨论】:

    标签: swift xcode swift3 spotify


    【解决方案1】:
    var auth = SPTAuth.defaultInstance()!
    var session:SPTSession!
    

    首先设置重定向 URL 和客户端 ID:

                let redirectURL = "xyz://" // put your redirect URL here
                auth.redirectURL     = URL(string: redirectURL)
                auth.clientID        = kClientId
                auth.requestedScopes = [SPTAuthStreamingScope, SPTAuthPlaylistReadPrivateScope, SPTAuthPlaylistModifyPublicScope, SPTAuthPlaylistModifyPrivateScope]
                loginUrl = auth.spotifyWebAuthenticationURL()
    

    然后使用登录方式:

            if UIApplication.shared.openURL(loginUrl!) {
    
                if auth.canHandle(auth.redirectURL) {
                    // To do - build in error handling
                }
            }
    

    如果您需要更多帮助,请告诉我。我在 Swift 中配置并在我的当前应用程序中使用它。

    【讨论】:

      【解决方案2】:

      在您的 AppDelegate 中:

       func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
      
                  let auth: SPTAuth = SPTAuth.defaultInstance()
                  auth.clientID = "Your-Client-Id"
                  auth.redirectURL = URL(string: "Your-Callback-URL")
                  auth.sessionUserDefaultsKey = "current session"
      
                  return true
        }
      
        func application(_ app: UIApplication, open url: URL, options: [UIApplication.OpenURLOptionsKey : Any] = [:]) -> Bool {
              let auth:SPTAuth = SPTAuth.defaultInstance()
      
              let authCallback: SPTAuthCallback = { error, session in
                  if let error = error {
                      print(error.localizedDescription)
                      return
                  }
                  auth.session = session
      
                  NotificationCenter.default.post(name: NSNotification.Name("sessionUpdated"), object: nil)
              }
      
              if auth.canHandle(url) {
                  auth.handleAuthCallback(withTriggeredAuthURL: url, callback: authCallback)
                  return true
              }
      
              return false
        }
      

      在您的初始视图控制器中,您的登录方法应该是这样的:

      func loginToSpotify {
              let auth:SPTAuth = SPTAuth.defaultInstance()
      
      //check if first time login
      
              if auth.session != nil {
                  if auth.session.isValid() {
                      //to your search page
                      return
                  }
      //refresh token
                  renewTokenAndShowSearchVC()
                  return
              }
      
              if SPTAuth.supportsApplicationAuthentication() {
                  UIApplication.shared.open(auth.spotifyAppAuthenticationURL(), options: [:], completionHandler: nil)
              } else {
                  let safari = SFSafariViewController(url: auth.spotifyWebAuthenticationURL())
                  present(safari, animated: true, completion: nil)
              }
          }
      
      func renewTokenAndShowSearchVC() {
      
              print("Refreshing token...")
      
              let auth:SPTAuth = SPTAuth.defaultInstance()
              auth.renewSession(auth.session) { (error, session) in
                  auth.session = session
      
                  if let error = error {
                      print("Refreshing token failed.")
                      print(error.localizedDescription)
                      return
                  }
                  //to your search page
              }
          }
      

      然后.. 在您的 View Controller 或 Model View 的某个地方,您可以通过从 SPTSession 调用 accessToken 来获取令牌,例如,如果您想搜索曲目(名称、艺术家和专辑):

         struct Track: {
                  let name: String
                  let artist: String
                  let album: String
      
                  init(name: String, artist: String, album: String) {
                      self.name = name
                      self.artist = artist
                      self.album = album
                  }
              }
      
           func search(query: String, callback: @escaping ([Track]) -> Void) -> Void {
      
                  let auth: SPTAuth = SPTAuth.defaultInstance()
                  let token = auth.session.accessToken
      
                  SPTSearch.perform(withQuery: query, queryType: .queryTypeTrack, accessToken: token, market: "Country_Code") { (error, result) in
                      if let error = error {
                          print(error.localizedDescription)
                          return
                      }
      
                      if let listPage = result as? SPTListPage, 
                      let items = listPage.items as? [SPTPartialTrack], 
                      let artist = items.first?.artists.first as? SPTPartialArtist {
      
                           let tracks = items.compactMap({ (pTrack) -> Track in
      
                                  let name: String = pTrack.name
                                  let artist: String = artist.name
                                  let album: String = pTrack.album.name
      
                                  return Track(name: name , artist: artist, album: album)
                              })
      
                              callback(tracks)
                          }
                      }
                  }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2014-04-30
        • 2023-03-09
        • 2017-09-16
        • 1970-01-01
        • 2017-10-24
        • 2020-07-05
        • 1970-01-01
        相关资源
        最近更新 更多