Alamofire request with authorization bearer token and additional headers Swift

Viewed 6385

My API includes authorization bearer token and three additional headers. My problem is I'm not sending the bearer token right (Postman return the correct data not my simulator). I see a lot of examples for using the request adapter but can I not use that? Thanks!

The auth is actually in the authorization tab not in the header.

enter image description here

**Updated: Solved the problem by following the documentation. HTTP Headers

Here is the Alamofire function with working codes:

 func getBetsData(completion: ((Bool) -> ())? = nil) {

        guard let token = defaults.string(forKey: "token") else {
            return
        }

        let headers: HTTPHeaders = [
        .authorization(bearerToken: token),
        .init(name: "bet_type", value: type),
        .init(name: "bet_status", value: status),
        .init(name: "page", value: String(page))
    ]

        AF.request("https://example.com", headers: headers).responseDecodable(of: Bets.self) { response in
            switch response.result {
            case .success:
                if let data = response.data {

                    do {
                        let bets = try JSONDecoder().decode(Bets.self, from: data)
                        print("message: \(bets.message)")                      

                        self.setupTableData()
                        completion?(true)
                    } catch {
                        print("Error: \(error)")
                        completion?(false)
                    }
                }
            case.failure(let error):
                print(error)
                completion?(false)
            }
        }
    }
2 Answers

You can add the headers directly:

let headers: HTTPHeaders = [.authorization(bearerToken: token)]

Additionally, if you're decoding a Decodable value from the response, you should not use responseJSON, as that decodes the Data using JSONSerialization and then you just parse it again. Instead, you should use responseDecodable.

AF.request(...).responseDecodable(of: Bets.self) { response in
    // Use response.
}

That will be much more efficient and will capture errors for you automatically.

As mention by Dilan only token is not enought you will need to Bearer in the same Header parameter.

Here is one of the best method to handle Token Request and Retrier in all the request you send to server in the application

https://www.avanderlee.com/swift/authentication-alamofire-request-adapter/

By this you don't need to handle token manually in all the webservice.

Related