swift - 在 Spotify iOS SDK 中设置授权 token

标签 swift xcode swift3 spotify

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/

相关文章:

iPhone 应用程序在启动时崩溃,不明白为什么

ios - IQKeyboardManager 在我的 View Controller 中无法正常工作

ios - 预期返回 'UITableViewCell' 的函数中缺少返回值

ios - 如何在 Swift 中分配 CoreData 多对多关系?

iPhone Objective-C 从数据模型生成的文件中出现错误

php - Swift 3 如何转换此函数以返回 json 变量的内容

swift - 我需要帮助将特定的 UIImage 调整大小扩展集成到我当前的绘制 CGRect 函数中

ios - 在 UICollectionView 中解析本地 JSON 文件

ios - 下载 header 为 "Authorization"的文件时出现 400 错误

iOS - 按下按钮时关闭键盘