SendGrid API 在 Swift 中使用 URLSession 请求

SendGrid API Request in Swift with URLSession

我正在尝试使用 Swift 4URLSession 向 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 数据进行两次编码。删除此行

let ready = try! JSONEncoder().encode(data) // <-- !!! Crash !!!

然后简单地做

do {
  let data = try JSONSerialization.data(withJSONObject: json, options: [])
  request.httpBody = data
} catch {
   print("\(error)")
}

此外,如果可以避免,请不要使用 try!