Search code examples
http-headersswift2alamofire

Alamofire header throwing error: Cannot convert value of type to expected type


I am trying to make a POST request with Alamofire (header token authentication) but I am being thrown an error

Cannot convert value of type '[String:String]' to expected argument type '[String:String]'

Token header error

How can I fix it?

This is my code:

func validationSuccessful() {

    let Auth_header = [ "Authorization" : Data.sharedInstance.token ]

    Alamofire.Manager.sharedInstance.request(.POST, Data.weeklyEndpoint, headers: Auth_header, parameters: ["username": Data.sharedInstance.userName!, "password": Data.sharedInstance.passWord!]).responseJSON {
        response in

        if let result = response.result.value
        {
            print(response.request)
            print(response.response)
            print(response.result)

        }
        else
        {
            print("JSON data is nil.")
        }
    }

}

Solution

  • Your Data.sharedInstance.token is an optional... To fix this you can write

    let Auth_header = [ "Authorization" : Data.sharedInstance.token ?? "" ]
    

    But you should check if your token is nil first. For example:

    guard let token = Data.sharedInstance.token else { print("Empty token"); return }
    let Auth_header = [ "Authorization" : token ]