Alamofire: how to add json array parameter to data with multiple data?

I will try to send the photo along with the parameters, but to catch that I want to send a JSON array to the server. Alamofire doesn't seem to have a way to post a list Data, so another good alternative to this?

key part of the problem:

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

as part of this download 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)

            }
        }
    }
+4
source share
5 answers

You can do the following:

Alamofire.upload(multipartFormData: { (multipartFormData) in
       multipartFormData.append(imageData, withName: "xyz", fileName: "file.jpeg", mimeType: "image/jpeg") // append data what you want
}, to: url) 
{ (result) in
      //result
}
0
source

I had the same situation, you need to convert the array to a string, then encode and load. In my case, I had to encrypt the array and send the server, and then the server decrypts the array.

var encodedTags = tags.map({ return $0})
 //write logic to convert array to string
 mpd.append(encodedTags.data(using: .utf8)!, withName: key)
0

Here is the answer for a multi-page request, please view the code.

Alamofire.upload(multipartFormData:{ multipartFormData in
        let firstNameTxt = self.firstNmae.text!.data(using: .utf8)
        multipartFormData.append(firstNameTxt!, withName: "first_name", mimeType: "text/plain")
    },
                     usingThreshold:UInt64.init(), to:AppConstant.GlobalConstants.updateProfile, method:.post, headers:["Authorization": "auth_token"],encodingCompletion: { encodingResult in
                        switch encodingResult {
                        case .success(let upload, _, _):
                            upload.responseJSON { response in
                                debugPrint(response)
                            }
                        case .failure(let encodingError):
                            print(encodingError)
                        }
    })
0
source

Ok, so I used JSONSerialization. It converts my list to an object Any, which I convert to 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 {}

    }
0
source

If you want to do this with Swift 4, you can use the new JSONEncoder. You could do something similar to upload a file and a JSON parameter using data with multiple forms:

let image = UIImage(named: "test")
let png = UIImagePNGRepresentation(image!)!

let arr = ["str1", "str2"]
let jsonArr = try? JSONEncoder().encode(arr)

Alamofire.upload(multipartFormData: { (multiPart) in
    multiPart.append(png, withName: "file", fileName: "aaa.png", mimeType: "image/png")

    if let jsonArr = jsonArr {
        multiPart.append(jsonArr, withName: "pictures")
    }
}, to: URL) { (result) in
}
0
source

Source: https://habr.com/ru/post/1675580/


All Articles