OGeek|极客世界-中国程序员成长平台

标题: ios - Spotify API 授权错误 (Swift) [打印本页]

作者: 菜鸟教程小白    时间: 2022-12-11 18:18
标题: ios - Spotify API 授权错误 (Swift)

我用 Swift 制作了一个小应用程序,用户可以在其中搜索 Spotify 数据库中的歌曲。我正在使用 Web API 控制台 > 搜索项目。我的问题是新的 OAuth 系统,您必须在其中登录和所有这些东西。我的授权没问题,但是当我尝试使用以下代码获取访问 token 时,它返回以下错误:{"error":"server_error","error_description":"Unexpected status: 400"}。我的代码是:

    let keys = "<MY_APPLICATION_KEYS>"

    let url = NSURL(string: "https://accounts.spotify.com/api/token")

    let session = URLSession.shared

    let request = NSMutableURLRequest(url: url! as URL)

    request.httpMethod = "OST"

    request.setValue("Basic \(keys)", forHTTPHeaderField: "Authorization")

    request.setValue("client_credentials", forHTTPHeaderField: "grant_type")

    let task = session.dataTask(with: request as URLRequest) { (data, response, error) in

        guard let _: Data = data, let _: URLResponse = response, error == nil else {

            print(error!)
            return

        }

        let dataString = NSString(data: data!, encoding: String.Encoding.utf8.rawValue)
        print("Data: \(dataString!)")

        self.parseData(JSONData: data!)

    }

    task.resume()

}

var accessToken = ""

func parseData(JSONData : Data) {

    do {
        var readableJSON = try JSONSerialization.jsonObject(with: JSONData, options: .mutableContainers) as! JSONStandard

        if let token = readableJSON["access_token"] as? String {

            accessToken = token

        }

        print("Access Token: \(accessToken)")

        updateTokenInFirebase()

    }
    catch{
        print(error)
    }

任何帮助将不胜感激,非常感谢您!

Web API 文档:Web API Link

我在客户端凭据流上使用第一种方法。



Best Answer-推荐答案


我知道您发布此内容已经有大约 1 年的时间了,但我遇到了同样的问题,经过几次尝试后终于解决了。您可以在 Playground 中进行测试。

import Foundation
import PlaygroundSupport

PlaygroundPage.current.needsIndefiniteExecution = true

if let url = URL(string: "https://accounts.spotify.com/api/token") {
    var postRequest = URLRequest(url: url)
    postRequest.httpMethod = "OST"
    let bodyParams = "grant_type=client_credentials"
    postRequest.httpBody = bodyParams.data(using: String.Encoding.ascii, allowLossyConversion: true)

    let id = "your client id"
    let secret = "your secret"
    let combined = "\(id):\(secret)"
    let combo = "\(id):\(secret)".toBase64()
    postRequest.addValue("Basic \(combo)", forHTTPHeaderField: "Authorization")

    let task = URLSession.shared.dataTask(with: postRequest) { (data, response, error) in
        guard let data = data else {
            return
        }
        print(String(data: data, encoding: String.Encoding.utf8)!)
    }
    task.resume()
}


extension String {

    func fromBase64() -> String? {
        guard let data = Data(base64Encoded: self) else {
            return nil
        }

        return String(data: data, encoding: .utf8)
    }

    func toBase64() -> String {
        return Data(self.utf8).base64EncodedString()
    } 
}

关于ios - Spotify API 授权错误 (Swift),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45167554/






欢迎光临 OGeek|极客世界-中国程序员成长平台 (https://ogeek.cn/) Powered by Discuz! X3.4