英文:
Cannot convert value of type '[String : String]' to expected argument type 'HTTPHeaders?'
问题
I'm trying to send mail from my iOS app with Mailgun
and Alamofire
. I found [this piece of code] 1, but Xcode
generates an 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?
英文:
I´m trying to send mail from my iOS app with Mailgun
and Alarmofire
I found [this piece of code] 1 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?
答案1
得分: 28
你需要明确设置类型。
let headers: HTTPHeaders = [
"Authorization": "Basic MY-API-KEY",
"Content-Type": "application/x-www-form-urlencoded"
]
英文:
You need to set the type explicitly.
let headers : HTTPHeaders = [
"Authorization": "Basic MY-API-KEY",
"Content-Type" : "application/x-www-form-urlencoded"
]
答案2
得分: 1
To modify existing code create Dictionary extension 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 extension to cast it.
AF.request(url, method: requestMethod, parameters: nil, encoding: URLEncoding.default, headers: header?.toHeader())
英文:
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())
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论