错误请求:请求中没有照片

时间:2017-10-03 14:50:26

标签: api

我试图将我的应用程序中的图像发送到此处的电报机器人 https://newfivefour.com/swift-form-data-multipart-upload-URLRequest.html 这是代码

let BotToken = "12345"
let ChatID = "123"
func SendToTelegram()
{
    var request = URLRequest(url: URL(string: "https://api.telegram.org/bot"+BotToken+"/sendPhoto")!)
    request.httpMethod = "POST"
    let boundary = "Boundary-\(UUID().uuidString)"
    request.setValue("multipart/form-data; boundary=\(boundary)", forHTTPHeaderField: "Content-Type")

    let params = [:] as [String: String]

    UIGraphicsBeginImageContextWithOptions(ScreenImage.bounds.size, true, 0.0)
    ScreenImage.image?.draw(in: CGRect(x: 0, y: 0, width: ScreenImage.frame.size.width, height: ScreenImage.frame.size.height))
    let image = UIGraphicsGetImageFromCurrentImageContext()
    UIGraphicsEndImageContext()

    request.httpBody = createBody(parameters: params,
                                  boundary: boundary,
                                  data: UIImageJPEGRepresentation(image!, 0.7)!,
                                  mimeType: "image/jpg",
                                  filename: "hello.jpg")
    print(request.httpBody!)
    let task = URLSession.shared.dataTask(with: request) { data, response, error in
        guard let data = data, error == nil else {               // check for fundamental networking error
            return
        }
        do {
            let json = try JSONSerialization.jsonObject(with: data, options: .mutableContainers) as? AnyObject

            if let parseJSON = json {
                print("resp :\(parseJSON)")
            }
        } catch let error as NSError {
            print("error : \(error)")
        }
    }
    task.resume()
}

并收到错误

Bad Request: there is no photo in the request";
"error_code" = 400;
ok = 0;

我在哪里犯错?我是SWIFT的新人,对不起我的英语

1 个答案:

答案 0 :(得分:0)

我知道这个问题很旧,但是提供的链接将我推向了正确的方向。这是我针对服务器端Swift而不是iOS的解决方案,但是您应该可以进行最小的更改。请记住,如果您使用的是iOS,请不要在主线程上执行任何这些操作。

class NetworkManager {
    func sendTelegramPhoto(_ photo: Data) {
        let url = "https://api.telegram.org/bot\(Constants.Telegram.token)/sendPhoto"
        let params: [String: Any] = [
            "chat_id": Constants.Telegram.uid,
            "photo": photo
        ]

        let _ = sendMultiTypePostRequest(url, parameters: params)
    }

    private func sendMultiTypePostRequest(_ url: String, parameters: [String:String]) -> NetworkResponse {
        var networkResponse = NetworkResponse()
        let semaphore = DispatchSemaphore(value: 0)

        guard let url = URL(string: url) else {
            return networkResponse
        }

        var urlRequest = URLRequest(url: url)
        urlRequest.httpMethod = "POST"
        let boundary = "Boundary-\(UUID().uuidString)"
        urlRequest.setValue("multipart/form-data; boundary=\(boundary)", forHTTPHeaderField: "Content-Type")
        let httpBody = createBody(parameters: parameters,
                            boundary: boundary,                                
                            mimeType: "image/jpeg",
                            filename: "snapshot.jpg")

        let config = URLSessionConfiguration.default
        config.requestCachePolicy = .reloadIgnoringLocalCacheData
        let session = URLSession(configuration: config)

        let task = session.uploadTask(with: urlRequest, from: httpBody) { (data, response, error) in
            networkResponse.data = data
            networkResponse.response = response
            networkResponse.error = error
            semaphore.signal()
        }

        task.resume()

        _ = semaphore.wait(timeout: .distantFuture)

        return networkResponse
    }

    private func createBody(parameters: [String: String],
                        boundary: String,
                        mimeType: String,
                        filename: String) -> Data {
        var body = Data()

        let boundaryPrefix = "--\(boundary)\r\n"

        for (key, value) in parameters {
            if let data = value as? Data {
                body.appendString(boundaryPrefix)
                body.appendString("Content-Disposition: form-data; name=\"\(key)\"; filename=\"\(filename)\"\r\n")
                body.appendString("Content-Type: \(mimeType)\r\n\r\n")
                body.append(data)
                body.appendString("\r\n")
            } else if let string = value as? String {
                body.appendString(boundaryPrefix)
                body.appendString("Content-Disposition: form-data; name=\"\(key)\"\r\n\r\n")
                body.appendString("\(string)\r\n")
            }           
        }

        body.appendString("--".appending(boundary.appending("--")))

        return body
    }
}

private extension Data {
    mutating func appendString(_ string: String) {
        let data = string.data(using: String.Encoding.utf8, allowLossyConversion: false)
        append(data!)
    }
}