Search code examples
iosswiftalamofireaccess-tokenbearer-token

"Only valid bearer authentication supported" - error 400


// Spotify API
func callAlamo(url: String) {
    let headers = ["Authorization" : "---Removed token---"]

    Alamofire.request(url, method: .get, headers: headers).responseJSON(completionHandler: {
        response in
        print(response.result)
        print(response.result.value)
    })
}

Why does the code give me this error?

"Only valid bearer authentication supported" - error 400

enter image description here

I'm new to Alamofire, and it is hard to find lots of information on the internet, thanks!


Solution

  • Forgot about this post, but it was a real struggle for me so I will post my answer for others in the future.

    Here is the code I got in the end:

    public enum RequestResult {
        case success(JSONStandard)
        case failure(Error)
    }
    
    
    public func getAccessToken() {
        // Get new token
        let parameters = ["client_id" : clientID,
                          "client_secret" : clientSecret,
                          "grant_type" : "client_credentials"]
    
        func getAccessTokenClosure(completion: @escaping (RequestResult) -> ()) {
            Alamofire.request("https://accounts.spotify.com/api/token", method: .post, parameters: parameters).responseJSON(completionHandler: { response in
                // Check if response is valid
                if let accessToken = response.result.value as? JSONStandard {
                    completion(.success(accessToken))
                } else {
                    completion(.failure(_)) // Can fail with a custom error
                }
            })
        }
    
    
        getAccessTokenClosure { result in
            switch result {
            case .success(let token):
                // Success
            case .failure(_):
                // Failed, could be due to internet issues etc.
            }
        }
    }
    

    If you still have questions, ask me no matter how long ago this post was!