【发布时间】:2018-06-10 07:33:55
【问题描述】:
我正在尝试使用 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"]]
]
【问题讨论】:
标签: json swift sendgrid nsjsonserialization urlsession