【问题标题】:SendGrid API Request in Swift with URLSession带有 URLSession 的 Swift 中的 SendGrid API 请求
【发布时间】:2018-06-10 07:33:55
【问题描述】:

我正在尝试使用 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 swift sendgrid nsjsonserialization urlsession


    【解决方案1】:

    无需对 JSON 数据进行两次编码。删除此行

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

    然后做

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

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

    【讨论】:

    • 感谢您的帮助!
    • 我的 JSON 现在看起来还可以,但我不断收到 400 错误(错误请求)。
    • 没关系,我在我的问题中发布了修复它的更新。
    • Sendgrid 声明“所有响应都以 JSON 格式返回。我们通过发送 Content-Type 标头来指定这一点。”但是,我看到的是 text/plain 。回复还包括这个链接:sendgrid.com/docs/Classroom/Basics/API/cors.html 这是否意味着有问题?发送成功 - 我在预定目的地收到了电子邮件。
    猜你喜欢
    • 2017-04-10
    • 1970-01-01
    • 1970-01-01
    • 2021-08-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多