user20286225
user20286225

Reputation:

Swift: Sending Images Object via URLRequest

I have an array of an object that has the following values:

var pictures = [Pictures]

struct Pictures: Codable, Hashable {
  var picName1: String
  var picName2: String
  var picName3: String
  var picFile1: UIImage
  var picFile2: UIImage
  var picFile3: UIImage
}

And I want to send it to my API through URLRequest.

I am encountering some issues with HTTP structuring.

I keep getting the response: "Failed to read the request form. Multipart body length limit 16384 exceeded."

This is my network/API call code:

func sendPicturesToServer() {
    let url = URL(string: "https://myapicall.com/noodles")
    let body = try! JSONEncoder().encode(pictures)
    let boundary = "---------------------------14737809831466499882746641449"
    
    var request = URLRequest(url: url)
    request.httpMethod = "POST"
    request.setValue("multipart/form-data; boundary=\(boundary)", forHTTPHeaderField: "Content-Type")
    request.addValue("application/json", forHTTPHeaderField: "Accept")
    request.httpBody = body
    
    let task = URLSession.shared.dataTask(with: request) { (data, response, error) in
      guard let data = data, error == nil else {
        print(error?.localizedDescription ?? "No data")
        return
      }
      
      do {
        let serializedResponse = try JSONSerialization.jsonObject(with: data, options: .allowFragments)
          print("Serialized Response: \(serializedResponse)")
      } catch {
        print(error)
      }
    }
    task.resume()
  }
}

Anyone have any suggestions?

Upvotes: 0

Views: 414

Answers (1)

Rishi jha
Rishi jha

Reputation: 81

    func postApiDataWithMultipartForm<T:Decodable>(requestUrl: URL, request: ImageRequest, resultType: T.Type, completionHandler:@escaping(_ result: T)-> Void)
{
    var urlRequest = URLRequest(url: requestUrl)
    let lineBreak = "\r\n"

    urlRequest.httpMethod = "post"
    let boundary = "---------------------------------\(UUID().uuidString)"
    urlRequest.addValue("multipart/form-data; boundary=\(boundary)", forHTTPHeaderField: "content-type")

    var requestData = Data()

    requestData.append("--\(boundary)\r\n" .data(using: .utf8)!)
    requestData.append("content-disposition: form-data; name=\"attachment\" \(lineBreak + lineBreak)" .data(using: .utf8)!)
    requestData.append(request.attachment .data(using: .utf8)!)

    requestData.append("\(lineBreak)--\(boundary)\r\n" .data(using: .utf8)!)
    requestData.append("content-disposition: form-data; name=\"fileName\" \(lineBreak + lineBreak)" .data(using: .utf8)!)
    requestData.append("\(request.fileName + lineBreak)" .data(using: .utf8)!)

    requestData.append("--\(boundary)--\(lineBreak)" .data(using: .utf8)!)

    urlRequest.addValue("\(requestData.count)", forHTTPHeaderField: "content-length")
    urlRequest.httpBody = requestData

   // let multipartStr = String(decoding: requestData, as: UTF8.self) //to view the multipart form string

    URLSession.shared.dataTask(with: urlRequest) { (data, httpUrlResponse, error) in
        if(error == nil && data != nil && data?.count != 0)
        {
        // let dataStr = String(decoding: requestData, as: UTF8.self) //to view the data you receive from the API
            do {
                let response = try JSONDecoder().decode(T.self, from: data!)
                _=completionHandler(response)
            }
            catch let decodingError {
                debugPrint(decodingError)
            }
        }

    }.resume()

}

Upvotes: 0

Related Questions