我尝试使用 Swift 4 和URLSession
向SendGrid API发送请求。我希望不包含任何第三方依赖项,因为这是我的应用程序中唯一使用JSON和HTTP请求的地方。
由于SendGrid没有任何Swift示例,我正在查看cURL示例:
curl --request POST \
--url https://api.sendgrid.com/v3/mail/send \
--header "Authorization: Bearer $SENDGRID_API_KEY" \
--header 'Content-Type: application/json' \
--data '{"personalizations": [{"to": [{"email": "test@example.com"}]}],"from": {"email": "test@example.com"},"subject": "Sending with SendGrid is Fun","content": [{"type": "text/plain", "value": "and easy to do anywhere, even with cURL"}]}'
我认为我已经安排了所有内容,但我不确定如何将data
部分编码为请求的有效JSON。我尝试将其转换为Dictionary
,但它不起作用。这是我的代码:
let sendGridURL = "https://api.sendgrid.com/v3/mail/send"
var request = URLRequest(url: URL(string: sendGridURL)!)
request.httpMethod = "POST"
//Headers
request.addValue("Bearer \(sendGridAPIKey)", forHTTPHeaderField: "Authorization")
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
//Data
let json = [
"personalizations":[
"to": ["email":"test@example.com"],
"from": ["email":"test@example.com"],
"subject": "Sending with SendGrid is Fun",
"content":["type":"text/plain", "value":"and easy to do anywhere, even with Swift"]
]
]
let data = try! JSONSerialization.data(withJSONObject: json, options: [])
let ready = try! JSONEncoder().encode(data) <-- !!! Crash !!!
request.httpBody = ready
有没有人从可以帮助我的Swift应用程序中取出同样的东西?
更新
对于任何试图做同样事情的人,我不得不调整我的JSON看起来像这样才能为SendGrid正确格式化它:
let json:[String:Any] = [
"personalizations":[["to": [["email":"test@example.com"]]]],
"from": ["email":"test@example.com"],
"subject": "Sending with SendGrid is Fun",
"content":[["type":"text/plain", "value":"and easy to do anywhere, even with Swift"]]
]
答案 0 :(得分:2)
无需对JSON数据进行两次编码。删除此行
let ready = try! JSONEncoder().encode(data) // <-- !!! Crash !!!
然后简单地做
do {
let data = try JSONSerialization.data(withJSONObject: json, options: [])
request.httpBody = data
} catch {
print("\(error)")
}
另外,如果可以避免,请不要使用try!
。