8

I´m trying to send mail from my iOS app with Mailgun and Alarmofire I found this piece of code but Xcode generates error:

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

Code:

let parameters = [
                   "from": "sender@whatyouwant.com",
                     "to": "anyRecipient@example.com",
                "subject": "Subject of the email",
                   "text": "This is the body of the email."]
    let header = [
            "Authorization": "Basic MY-API-KEY",
            "Content-Type" : "application/x-www-form-urlencoded"]

    let url = "https://api.mailgun.net/v3/MY-DOMAIN/messages"
    Alamofire.request(url,
                   method: .post,
               parameters: parameters,
                 encoding: URLEncoding.default,
                  headers: header)
            .responseJSON { response in
                print("Response: \(response)")
                }

Any suggestions?

PerNil
  • 187
  • 1
  • 11

2 Answers2

28

You need to set the type explicitly.

let headers : HTTPHeaders = [
    "Authorization": "Basic MY-API-KEY",
    "Content-Type" : "application/x-www-form-urlencoded"
]
emeraldsanto
  • 4,330
  • 1
  • 12
  • 25
  • 1
    Better yet, use the strongly typed versions of those headers: `.authorization("Basic MY-API-KY)` and `.contentType("application/x-www-form-urlencoded")`. And you don't need to set a content type, the parameter encoding / encoder will do that for you. – Jon Shier Jan 06 '20 at 19:52
  • Yeap, this happened to the solution for the older definition with [String: String].. same but the type should be HTTP headers – Rakshitha Muranga Rodrigo Nov 10 '21 at 08:18
1

To modify existing code create Dictionary exention to cast from [String: String] to HTTPHeaders.

extension Dictionary where Key == String, Value == String {
    func toHeader() -> HTTPHeaders {
        var headers: HTTPHeaders = [:]
        for (key, value) in self  {
            headers.add(name: key, value: value)
        }
        return headers
    }
}

and use this extention to cast it.

AF.request(url, method: requestMethod, parameters: nil, encoding: URLEncoding.default ,headers: header?.toHeader())