【问题标题】:Cannot convert value of type '[String : String]' to expected argument type 'HTTPHeaders?'无法将类型“[String : String]”的值转换为预期的参数类型“HTTPHeaders?”
【发布时间】:2020-01-03 14:45:32
【问题描述】:

我正在尝试使用 MailgunAlarmofire 从我的 iOS 应用程序发送邮件我发现 this piece of codeXcode 生成错误:

无法将“[String : String]”类型的值转换为预期参数 输入“HTTPHeaders?”

代码:

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)")
                }

有什么建议吗?

【问题讨论】:

    标签: swift alamofire mailgun


    【解决方案1】:

    您需要明确设置类型。

    let headers : HTTPHeaders = [
        "Authorization": "Basic MY-API-KEY",
        "Content-Type" : "application/x-www-form-urlencoded"
    ]
    

    【讨论】:

    • 更好的是,使用这些标头的强类型版本:.authorization("Basic MY-API-KY).contentType("application/x-www-form-urlencoded")。而且你不需要设置内容类型,参数 encoding/encoder 会帮你搞定的。
    • 是的,这发生在使用 [String: String] 的旧定义的解决方案中。相同但类型应该是 HTTP 标头
    【解决方案2】:

    要修改现有代码,请创建字典扩展以从 [String: String] 转换为 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
        }
    }
    

    并使用这个扩展来投射它。

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

    【讨论】:

      猜你喜欢
      • 2016-01-14
      • 1970-01-01
      • 1970-01-01
      • 2020-12-30
      • 2021-03-13
      • 2015-12-24
      • 1970-01-01
      • 2023-04-05
      • 1970-01-01
      相关资源
      最近更新 更多