Spotify iOS SDK 全部采用 objective-c,截至今天,使用 SDK 的任何请求似乎都需要 token 。当我尝试搜索歌曲时,出现此错误:
["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 中设置 token ?
最佳答案
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 中配置并在我当前的应用程序中使用它。
关于swift - 在 Spotify iOS SDK 中设置授权 token ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44251845/