Shruti Shruti - 4 years ago 1216
Swift Question

Sending Image to server with parameters in Swift

I am trying to send Image on the server with

parameter using Alamofire. But on the server they are able to receive the image but not the
i am sending. Below is the code that i am using:

let parameters: [String : String] = [
"preferredVenueType": "club",
"userId": "1"
let urlRequest = urlRequestWithComponents(baseURL + uploadImage, parameters: parameters , imageData: imageData!)
upload(urlRequest.0, data: urlRequest.1)
.progress { (bytesWritten, totalBytesWritten, totalBytesExpectedToWrite) in
//print("\(totalBytesWritten) / \(totalBytesExpectedToWrite)")
.responseJSON {response in
if let JSON = response.result.value {
print("JSON: \(JSON)")

func urlRequestWithComponents(urlString:String, parameters:Dictionary<String, String>, imageData:NSData) -> (URLRequestConvertible, NSData) {

// create url request to send
let mutableURLRequest = NSMutableURLRequest(URL: NSURL(string: urlString)!)
mutableURLRequest.HTTPMethod = Method.POST.rawValue
let boundaryConstant = "myRandomBoundary12345";
let contentType = "multipart/form-data;boundary="+boundaryConstant
mutableURLRequest.setValue(contentType, forHTTPHeaderField: "Content-Type")

// mutableURLRequest.HTTPBody = jsonData

// create upload data to send
let uploadData = NSMutableData()

// add image
uploadData.appendData("Content-Disposition: form-data; name=\"profileImage\"; filename=\"profileImage.png\"\r\n".dataUsingEncoding(NSUTF8StringEncoding)!)
uploadData.appendData("Content-Type: image/png\r\n\r\n".dataUsingEncoding(NSUTF8StringEncoding)!)

// add parameters
for (key, value) in parameters {
uploadData.appendData("Content-Disposition: form-data; name=\"\(key)\"\r\n\r\n\(value)".dataUsingEncoding(NSUTF8StringEncoding)!)
// uploadData.appendData("Content-Disposition: form-data; name=\"json\"\r\n\r\n".dataUsingEncoding(NSUTF8StringEncoding)!)


// return URLRequestConvertible and NSData
return (ParameterEncoding.URL.encode(mutableURLRequest, parameters: nil).0, uploadData)


I am getting error message in response as they are unable to receive the
data along with the image file.

Answer Source

I solved my Problem by sending parameters as a JSON String instead of key value pairs.

 let parameters: [String : String] = [
            "preferredVenueType": prameterText,
            "userId": userId,
         var theJSONText : NSString  = ""

        do {
            let theJSONData = try NSJSONSerialization.dataWithJSONObject(
                parameters ,
                options: NSJSONWritingOptions(rawValue: 0))
            theJSONText = NSString(data: theJSONData,
                encoding: NSASCIIStringEncoding)!
            // due to some reason NSUTF8StringEncoding was not working so i used ASCII encoding
        } catch let error as NSError {

And while sending it to server i used

let uploadData = NSMutableData()

        uploadData.appendData("Content-Disposition: form-data; name=\"json\"\r\n\r\n".dataUsingEncoding(NSUTF8StringEncoding)!)

After sending parameters as a JSON String the data was successfully uploaded to server.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download