使用Swift向Discord Webhook发送HTTP POST请求会导致响应错误

时间:2019-10-07 09:46:40

标签: ios discord xcode11 swift5

我正在尝试在Swift中创建URL请求,以将HTTP POST请求发送到Discord Webhook,并且该请求在定义为“ responseProblem”的失败中完成。我不确定响应问题的来源。

从技术上讲,Discord应该能够接受HTTP请求,并且对该问题的大量研究使我无所适从。我以前曾经与Discord webhooks一起工作过,但是以前我从未玩过这种东西,所以对于现在应该做的事情我还是有些困惑。

import Foundation

enum APIError:Error {
    case responseProblem
    case decodingProblem
    case encodingProblem
}


struct APIRequest {
    let resourceURL: URL

    init(endpoint: String) {
        let resourceString = "<discord-webhook-url-removed-for-privacy>"
        guard let resourceURL = URL(string: resourceString) else {fatalError()}

        self.resourceURL = resourceURL

    }

    func save (_ messageToSave:Message, completion: @escaping(Result<Message, APIError>) -> Void ) {

        do {
            var urlRequest = URLRequest(url: resourceURL)
            urlRequest.httpMethod = "POST"
            urlRequest.addValue("application/json", forHTTPHeaderField: "Content-Type")
            urlRequest.httpBody = try JSONEncoder().encode(messageToSave)

            let dataTask = URLSession.shared.dataTask(with: urlRequest) { data, response, _ in
                guard let httpResponse = response as? HTTPURLResponse, httpResponse.statusCode == 200, let
                    jsonData = data else {
                        completion(.failure(.responseProblem)) // <<< 'responseProblem' is outputted in console as the error
                        return
                }

                do {
                    let messageData = try JSONDecoder().decode(Message.self, from: jsonData)
                    completion(.success(messageData))
                } catch {
                    completion(.failure(.decodingProblem))
                }

            }
            dataTask.resume()
        } catch {
            completion(.failure(.encodingProblem))
        }

    }

}

当我运行这个Swift程序时,我希望它向Discord Webhook发送一个请求,以将消息发送到它的指定通道。但是,输出到控制台的唯一错误是responseProblem。请让我知道是否需要进一步添加内容以解决问题的根本原因(我对Swift还是半新鲜的,而且我通常使用JavaScript,因此我不确定如何正确调试Swift和Xcode。)

Swift应用程序内置于iOS 12.2中,因为Xcode在iOS 13中不喜欢这种东西

1 个答案:

答案 0 :(得分:0)

这是我使用Swift发布到Discord Webhook的简化版本。从您的文章中,我看不到如何将自定义Message结构转换为JSON字典,但是您至少需要“内容”的键/值对才能成功发布Discord Webhook。当然,帖子可以通过其他多种方式进行自定义(使用自定义的“用户名”等)。

    var messageString: String = ""

    guard let url = URL(string: "your-full-discord-webhook-url") else { return }
    let messageJson: [String: Any] = ["content": messageString]
    let jsonData = try? JSONSerialization.data(withJSONObject: messageJson)
    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()