1

I have a screen on my app that I get some fields and save on my object Order. This object is my Core Data Object. After saving it, I need to send it to my backend through Alamofire POST multipartFormData. The problem is that this is a Core Data Object (not Codable) and I need to send Data type on multipartFormData. How can I convert my object to Data? Is there another way of doing it?

What I've done:

let order = Order(context: DatabaseController.getContext())
order.orderItem = orderItem
order.product = product
order.value = value
order.date = date

Alamofire part:

Alamofire.upload (
            multipartFormData: { multipartFormData in

                multipartFormData.append(order, withName: "order")
            },
            to: url,
            headers: headers,
            encodingCompletion: { encodingResult in

The problem is how to put my object Order inside multipartFormData? Could anyone help me please?

Updated:

Ok, sending the whole object didn't work, my api didn't accept, so I made a specific json only with the fields needed and turned it a Data type: (PS: files are Data type from images user choose, even from camera or gallery)

var files = Dictionary<Data, String>()
var jsonFiles = [[String: String]]()
var jsonOrder = [String: Any]()

for file in files {
    let dict : [String: String] = [ "orderImageIdLocal": uuidOrderImageIdLocal,
                                    "orderItemAnalysisIdLocal": uuidAnalysisIdLocal,
                                    "urlImageLocal": "\(imageId).jpg"]
    jsonFiles.append(dict)
}
jsonOrder = [ "reason": "\(textViewReason)",
                          "orderImagess": jsonFiles,
                          "orderAnalysisId": "",
                          "orderIdLocal": "\(uuidAnaliseIdLocal)",
                          "orderId": "\(orderId ?? "")",
                          "typeSolicitation": "\(typeSolicitation)"]

Then I convert it to Data type like you said and send to Alamofire like above:

let orderData = try? JSONSerialization.data(withJSONObject: jsonOrder, options: .prettyPrinted) {

My problem now is that my api expect a zip file with those images user took from camera or gallery. So I am trying to use ZIPFoundation. I still don't know how to zip it and send. Should I zip each picture as Data type? Then transform zip file into Data type so I can send through multipartFormData.append?

I have tried: here and here

asr
  • 139
  • 3
  • 11
  • Do you have access to the source code your api method on server? Can you post that? In that case it will be clear what your api exactly expecting – Neil Galiaskarov Feb 27 '19 at 19:03

1 Answers1

3

Here the code as an extension of NSManagedObject which creates dictionary from the attributes name.

extension NSManagedObject {
  func toData() -> Data? {
    let keys = Array(self.entity.attributesByName.keys)
    let dict = self.dictionaryWithValues(forKeys: keys)
    do {
        let jsonData = try JSONSerialization.data(withJSONObject: dict, options: .prettyPrinted)
        return jsonData
    }
    catch{}
    return nil
  }
}

Usage:

let jsonData = order.toData()
multipartFormData.append(jsonData, withName: "order")
Neil Galiaskarov
  • 5,015
  • 2
  • 27
  • 46
  • Ok, your solution works. But my logic is wrong. I need to send a package of images and this order object. How can I do that? When I use Alamofire.request, I can send "parameters" as json object. But sending a package of images I should use upload, right? So I don't have parameters. Since I still need to send some images. Could you help please? – asr Feb 25 '19 at 18:55
  • Can you update your question with details and your server restapi functions, (what your is expecting to receive)? and i will try to help you – Neil Galiaskarov Feb 26 '19 at 07:41