vn_serg vn_serg - 6 months ago 89
Swift Question

How add Int vaue to the Alamofire upload parameters

I want to add Int value to the multipartFormData:

Alamofire.upload(.POST,
URL,
headers: headers,
multipartFormData: { multipartFormData in
//add some jpg image
//add other vaues:
for (key, value) in parameters {
if value is String {
multipartFormData.appendBodyPart(data: value.dataUsingEncoding(NSUTF8StringEncoding)!, name: key)
} else if value is Int {
let convertedValueNumber: NSNumber = NSNumber(int: value.intValue)
let data = NSKeyedArchiver.archivedDataWithRootObject(convertedValueNumber)
multipartFormData.appendBodyPart(data: data, name: key)
}
}

}, encodingCompletion: { encodingResult in
//some processing
})


But server return error that I don't send Int value. How Add Int vaue to the parameters?

Rob Rob
Answer

The NSKeyedArchiver is very curious. Usually you'd just send string representation, e.g.:

Alamofire.upload(.POST,
                         URL,
                         headers: headers,
                         multipartFormData: { multipartFormData in
                            //add some jpg image
                            //add other vaues:
                            for (key, value) in parameters {
                                if value is String {
                                    multipartFormData.appendBodyPart(data: value.dataUsingEncoding(NSUTF8StringEncoding)!, name: key)
                                } else if value is Int {
                                    multipartFormData.appendBodyPart(data: "\(value)".dataUsingEncoding(NSUTF8StringEncoding)!, name: key)
                                }
                            }
            }, encodingCompletion: { encodingResult in
              //some processing
        })