Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How add Int value 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 do I add Int value to the parameters?

like image 833
biloshkurskyi.ss Avatar asked May 23 '16 18:05

biloshkurskyi.ss


1 Answers

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 values:
    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
})

Or, even simpler, because string interpolation works with both String and Int:

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

Or, in Alamofire 4 with Swift 3:

Alamofire.upload(multipartFormData: { multipartFormData in
    //add some jpg image
    //add other values:
    for (key, value) in parameters {
        if value is String || value is Int {
            multipartFormData.append("\(value)".data(using: .utf8)!, withName: key)
        }
    }
}, to: url, method: .post, headers: headers, encodingCompletion: { encodingResult in
    //some processing
})
like image 140
Rob Avatar answered Oct 21 '22 21:10

Rob