Search code examples
iosswiftupload

How to upload Data to API?


I need to upload Data to API. Parameters:

ScreenShot

I have next code:

static func uploadNewInfo(uploadData: Data) {
        if let url = URL(string: TaskManager.httpString + "sett_eic.htm") {
            var request = URLRequest(url: url)
            request.httpMethod = "POST"
            request.httpBody = uploadData
            request.setValue("multipart/form-data", forHTTPHeaderField: "Content-Type")
            let task = URLSession.shared.dataTask(with: request) { (data, response, error) in
                if error == nil {
                    print("uploaded")
                }
            }
//            let task = URLSession.shared.uploadTask(with: request, from: uploadData) { (data, response, error) in
//                if error == nil {
//                    print("uploaded")
//                }
//            }
            task.resume()
        }
    } 

But response is:

"500 Internal Server Error: Expected data not present\r\n"

I don't understand how can I upload this data. I read some answers about how to upload Image, but don't understand it. My data is not Image. It's bytes, which describes Names, states, etc.

Update

This is how request looks in browser:

Screenshot2

Part with PRF64... - uploadData


Solution

  • You can try this:

    func uploadNewInfo(uploadData: Data) {
        let boundry = "**********"
        if let url = URL(string: TaskManager.httpString + "sett_eic.htm") {
            var request = URLRequest(url: url)
            request.httpMethod = "POST"
            //        request.httpBody = uploadData
            request.addValue("multipart/form-data; boundary=\(boundry)", forHTTPHeaderField: "Content-Type")
            var dataForm = Data()
            dataForm.append("\r\n--\(boundry)\r\n".data(using: .utf8)!)
            dataForm.append("Content-Disposition: form-data; name=\"param1\";\r\n\r\n10001".data(using: .utf8)!)
            dataForm.append(uploadData)
            dataForm.append("\r\n--\(boundry)--\r\n".data(using: .utf8)!)
            request.httpBody = dataForm
    
            let task = URLSession.shared.dataTask(with: request) { (data, response, error) in
                if error == nil {
                    print("uploaded")
                }
            }
            task.resume()
        }
    }
    

    Please let me know if it works :)