无法将类型“[String : String]”的值转换为预期的参数类型 'HTTPHeaders?'
Cannot convert value of type '[String : String]' to expected argument type 'HTTPHeaders?'
我正在尝试使用 Mailgun
和 Alarmofire
从我的 iOS 应用程序发送邮件 我发现 this piece of code 但 Xcode
生成错误:
Cannot convert value of type '[String : String]' to expected argument
type '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)")
}
有什么建议吗?
您需要明确设置类型。
let headers : HTTPHeaders = [
"Authorization": "Basic MY-API-KEY",
"Content-Type" : "application/x-www-form-urlencoded"
]
要修改现有代码,请创建字典扩展以从 [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())
我正在尝试使用 Mailgun
和 Alarmofire
从我的 iOS 应用程序发送邮件 我发现 this piece of code 但 Xcode
生成错误:
Cannot convert value of type '[String : String]' to expected argument type '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)")
}
有什么建议吗?
您需要明确设置类型。
let headers : HTTPHeaders = [
"Authorization": "Basic MY-API-KEY",
"Content-Type" : "application/x-www-form-urlencoded"
]
要修改现有代码,请创建字典扩展以从 [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())