gpt4 book ai didi

json - 带有 URLSession 的 Swift 中的 SendGrid API 请求

转载 作者:行者123 更新时间:2023-11-28 11:56:58 26 4
gpt4 key购买 nike

我正在尝试使用 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!

关于json - 带有 URLSession 的 Swift 中的 SendGrid API 请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50781508/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com