It seems that this question has been asked before, but no answers were very helpful to me. I have an app where I created my own ImagePicker to select more than one image from the user's Camera Roll. I now need to upload these images to a PHP script. Everything is working when I need to upload only a single image. The thing is, I have no idea how to change my code to upload multiple images.
Code to begin post (Only most important code related to upload)
let param = ["request":"uploadImagesAndParams", "someParam": self.txtSomeTextField.text!]
let boundary = generateBoundaryString()
request.setValue("multipart/form-data; boundary=\(boundary)", forHTTPHeaderField: "Content-Type")
//Here I am just selecting the first image in my UIImage array (selectedImages). I need to be able to select all of them and upload it.
let imageData = UIImageJPEGRepresentation((selectedImages?[0])!, 1)
if(imageData == nil) { return; }
request.httpBody = createBodyWithParameters(parameters: param,
filePathKey: "image",
imageDataKey: imageData! as NSData,
boundary: boundary) as Data
Code to upload
//Upload Function
func createBodyWithParameters(parameters: [String: String]?, filePathKey: String?, imageDataKey: NSData, boundary: String) -> NSData {
let body = NSMutableData();
if parameters != nil {
for (key, value) in parameters! {
body.appendString(string: "--\(boundary)\r\n")
body.appendString(string: "Content-Disposition: form-data; name=\"\(key)\"\r\n\r\n")
body.appendString(string: "\(value)\r\n")
}
}
let filename = "user-profile.jpg"
let mimetype = "image/jpg"
body.appendString(string: "--\(boundary)\r\n")
body.appendString(string: "Content-Disposition: form-data; name=\"\(filePathKey!)\"; filename=\"\(filename)\"\r\n")
body.appendString(string: "Content-Type: \(mimetype)\r\n\r\n")
body.append(imageDataKey as Data)
body.appendString(string: "\r\n")
body.appendString(string: "--\(boundary)--\r\n")
return body
}
func generateBoundaryString() -> String {
return "Boundary-\(NSUUID().uuidString)"
}