Search code examples
swiftswiftuidiscordwebhooks

Discord Webhooks newline in content


I just created this simple swift function that can send user feedback to a discord webhook but is has a problem. The function mostly works, UNLESS there is a newline in the msg string which causes the message to not be send. Can anyone help me there?

Here’s the swift function:

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()
}
}

Solution

  • A new line by itself is not valid JSON data. You can use new lines in a JSON string if you escape the new lines.

    For example:

     msg.replacingOccurrences(of: "\n", with: "\\n")
    

    either in the call

    sendFeedback(msg.replacingOccurrences(of: "\n", with: "\\n"))
    

    or in your

    "content": "\(msg.replacingOccurrences(of: "\n", with: "\\n"))"
    

    Use a similar approach for other new line representations, \r, or \r\n