我刚刚创建了这个简单的 swift 函数,它可以将用户反馈发送到不和谐的 webhook,但有一个问题。该函数大部分情况下都有效,除非消息字符串中存在换行符,导致消息无法发送。有人可以帮我吗?
这是 swift 函数:
import SwiftUI
func sendFeedback(_ msg: String) {
if let url = URL(string: "full_weebhook_url") {
let json = """
{
"username": "\(Date.now.formatted(date: .long, time: .complete))",
"content": "\(msg)",
"embeds": [{
"fields": [
{
"name": "Device Name",
"value": "\(UIDevice.current.name)"
},
{
"name": "Device Model",
"value": "\(UIDevice.current.model)"
},
{
"name": "Device Operating System",
"value": "\(UIDevice.current.systemName)"
},
{
"name": "Device Operating System Version",
"value": "\(UIDevice.current.systemVersion)"
}
]
}]
}
"""
print(json)
var request = URLRequest(url: url)
request.httpMethod = "POST"
request.addValue("application/json", forHTTPHeaderField: "content-type")
request.httpBody = json.data(using: .utf8)
let task = URLSession.shared.dataTask(with: request)
task.resume()
}
}
新行本身不是有效的 JSON 数据。你可以 如果转义新行,请在 JSON 字符串中使用新行。
例如:
msg.replacingOccurrences(of: "\n", with: "\\n")
无论是在通话中
sendFeedback(msg.replacingOccurrences(of: "\n", with: "\\n"))
或者在你的
"content": "\(msg.replacingOccurrences(of: "\n", with: "\\n"))"