0

now I'm using Alamofire to connecting my iOS app to server with apis.

Our server guy made post request that upload images and some information of this.

And this data send to server with POST method and multipart.

    private let files = UIImage(named: "testImg")!.pngData()!
    private let payload : [String : [String : String]] = [
        "postInfo" : [
            "title" : "iOS Test",
            "price" : "1000",
            "description" : "iOS Test",
            "category" : "iOS Test",
            "camps" : "[1,2]"
        ]
    ]

this is my parameters. And,

func upload() {
        AF.upload(multipartFormData: { [weak self] (multipartFormData) in
            guard let self = self else { return }
            // image
            multipartFormData.append(self.files, withName: "files", fileName : "testImg.png", mimeType: "image/png")
            
            // postInfo <- **this part I have in trouble**
            for (key, value) in self.payload {
                multipartFormData.append("\(value)".data(using: .utf8)!, withName: key, mimeType: "application/json")
            }
         

...             
          

I think nested parameter 'postInfo' does not send well to api.

So how can I send this nested json parameter 'postInfo' with multipart form data?

999rimmy
  • 35
  • 3
  • 1
    What does expect your server? For instance, if it expects JSON, maybe you want to call `JSONSerialization`, so it be, removing here the for loop, just: `multipartFormData.append(try? JSONSerialization.data(withJSONObject: payload["postInfo"]) ?? Data(), withName: "postInfo", mimeType: "application/json")`? – Larme Oct 02 '21 at 17:40
  • "And this data send to server with POST method and multipart" What do you mean by that? You mean, you are accessing your server through a PHP script or something? If so, it's up to what's written there. – El Tomato Oct 02 '21 at 22:24
  • The ky-value part at the end does not appear correct. – El Tomato Oct 02 '21 at 22:27

0 Answers0