Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Alamofire: how to append a json array parameter in a multipart form data?

I'm tryna send a photo along with parameters, but the catch is that I want to send a JSON array to the server. It seems Alamofire doesn't have a method to send a list of Data, so what's another good alternative to this?

the key part of the problem is:

var encodedTags: [Data] = tags.map({ return $0.data(using: .utf8)!})
            mpd.append(encodedTags, withName: key)

within this upload call:

let parameters: [String: Any] = ["username": "TheCooliest", ..., "tags": ["KoolKid", "TheKooliest", "BetterThanKimK"]    
...

upload(multipartFormData: { (mpd) in
        mpd.append(url, withName: "file", fileName: "weeknd.jpg")
        for (key, value) in parameters {
            if let tags = value as? [String], key == "tags" {
                var encodedTags = tags.map({ return $0.data(using: .utf8)!})
                mpd.append(encodedTags, withName: key)

            }
        }
    }
like image 214
rocky raccoon Avatar asked Nov 07 '22 22:11

rocky raccoon


1 Answers

Okay, so I used JSONSerialization. It converts my list into an Any object which I convert into Data.

for (key, value) in parameters {
    if let tags = value as? [String], key == "tags" {

        do {
            let json = try JSONSerialization.data(withJSONObject: tags, options: .prettyPrinted)
            mpd.append(json as Data, withName: key)
        } catch {}

    }
like image 83
rocky raccoon Avatar answered Nov 14 '22 23:11

rocky raccoon