You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Swift发送Discord Webhook时内容含换行导致发送失败求助

解决Discord Webhook发送含换行符消息失败的问题

问题出在你手动拼接JSON字符串的方式上:当msg包含换行符(\n)时,这些换行符会直接插入到JSON结构里,导致JSON格式无效——Discord的Webhook接口会拒绝解析格式错误的JSON,所以消息发送失败。

下面提供两种解决方案:

方案1:手动转义换行符

直接对msg中的换行符进行转义,把\n替换成JSON允许的\\n,修改content字段的拼接代码即可:

import SwiftUI

func sendFeedback(_ msg: String) {
    if let url = URL(string: "full_weebhook_url") {
        // 转义msg中的换行符
        let escapedMsg = msg.replacingOccurrences(of: "\n", with: "\\n")
        let json = """
        {
         "username": "\(Date.now.formatted(date: .long, time: .complete))",
         "content": "\(escapedMsg)",
         "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()
    }
}

注意:这种方法只能处理换行符,如果msg里包含双引号("),依然会破坏JSON结构,所以更推荐下面的方案。

方案2:使用Codable自动序列化JSON(推荐)

通过定义对应JSON结构的Swift结构体,利用JSONEncoder自动处理所有转义逻辑,彻底避免手动拼接JSON的各种格式问题:

import SwiftUI

// 定义对应Discord Webhook的结构体
struct WebhookPayload: Codable {
    let username: String
    let content: String
    let embeds: [Embed]
}

struct Embed: Codable {
    let fields: [Field]
}

struct Field: Codable {
    let name: String
    let value: String
}

func sendFeedback(_ msg: String) {
    guard let url = URL(string: "full_weebhook_url") else { return }
    
    // 构建字段数据
    let fields = [
        Field(name: "Device Name", value: UIDevice.current.name),
        Field(name: "Device Model", value: UIDevice.current.model),
        Field(name: "Device Operating System", value: UIDevice.current.systemName),
        Field(name: "Device Operating System Version", value: UIDevice.current.systemVersion)
    ]
    let embed = Embed(fields: fields)
    let payload = WebhookPayload(
        username: Date.now.formatted(date: .long, time: .complete),
        content: msg,
        embeds: [embed]
    )
    
    // 编码为JSON数据
    guard let jsonData = try? JSONEncoder().encode(payload) else {
        print("JSON编码失败")
        return
    }
    
    var request = URLRequest(url: url)
    request.httpMethod = "POST"
    request.addValue("application/json", forHTTPHeaderField: "content-type")
    request.httpBody = jsonData
    
    let task = URLSession.shared.dataTask(with: request)
    task.resume()
}

这种方式不仅能自动处理换行符,还能处理双引号、反斜杠等所有JSON特殊字符,代码可读性和健壮性都更高。

内容的提问来源于stack exchange,提问作者Karl Ehrlich

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.29 05:43:31