Upload multiple images in swift using Alamofire
Swift 3
Just use "[]" with image upload param to make it array of images.
Alamofire.upload(multipartFormData: { multipartFormData in
// import image to request
for imageData in imagesData {
multipartFormData.append(imageData, withName: "\(imageParamName)[]", fileName: "\(Date().timeIntervalSince1970).jpeg", mimeType: "image/jpeg")
}
for (key, value) in parameters {
multipartFormData.append(value.data(using: String.Encoding.utf8)!, withName: key)
}
}, to: urlString,
encodingCompletion: { encodingResult in
switch encodingResult {
case .success(let upload, _, _):
upload.responseJSON { response in
}
case .failure(let error):
print(error)
}
})
Multipart form data upload with multiple images + parameters (Alamofire 5.2)
try this code, I have not tested in Alamofire(5.2)
let baseUrl = "your URL"
let fullUrl = baseUrl + strUrl
var headers : HTTPHeaders = HTTPHeaders(["Content-type" : "multipart/form-data"])
if let header = header{
headers = header
}
guard let url = try? URLRequest(url: fullUrl, method: .post, headers: headers) else {return}
AF.upload(multipartFormData: { (multipartData) in
for i in 0 ..< arrImage.count{
if let imageData = arrImage[i].pngData(){
let mediaName = "media\(i + 1)"
multipartData.append(imageData, withName:mediaName, fileName: "\(Date().timeIntervalSince1970).jpg", mimeType: "file")
}
}
for (key, value) in parameter {
multipartData.append((value as AnyObject).data(using: String.Encoding.utf8.rawValue)!, withName: key)
}
}, to: url).responseJSON(queue: .main, options: .allowFragments) { (response) in
switch response.result{
case .success(let value):
print("Json: \(value)")
case .failure(let error):
print("Error: \(error.localizedDescription)")
}
}.uploadProgress { (progress) in
print("Progress: \(progress.fractionCompleted)")
}
Uploading multiple images(with parameters) using multipart form data - Alamofire 5
Try this method to upload multiple images
class func uploadImageWithURL(endPath : String, dictImage : [String:[UIImage]], parameter : [String : Any], header : HTTPHeaders? = nil, success : @escaping ( Any? )->Void, failure : @escaping (Error) -> Void){
let baseUrl = "your base URL"
let fullUrl = baseUrl + endPath
var headers = ["Content-type" : "multipart/form-data"]
if let header = header{
headers = header
}
let url = (try? URLRequest(url: fullUrl, method: .post, headers: headers))!
upload(multipartFormData: { (multipartData) in
for imagesData in dictImage {
for arrimage in imagesData.value{
multipartData.append(arrimage.jpegData(compressionQuality: 0.50)!, withName: imagesData.key, fileName: "\(Date().timeIntervalSince1970).jpg", mimeType: "image/jpeg")
}
}
for (key, value) in parameter {
multipartData.append((value as AnyObject).data(using: String.Encoding.utf8.rawValue)!, withName: key)
}
}, with: url) { (resultData) in
switch resultData{
case .success(let upload, let streamingFromDisk, let fileURL):
print("File URL : \(String(describing: fileURL))")
print("Streaming From Disk : \(streamingFromDisk)")
upload.uploadProgress(closure: { (progress) in
print("Progress : \(progress.fractionCompleted)")
})
upload.responseJSON(queue: nil, options: .allowFragments, completionHandler: { (response) in
if let value = response.result.value
{
success(value)
}
})
case .failure(let error):
failure(error)
print(error)
}
}
}
Upload multiple images in Alamofire
There are two ways to send multiple files.
You can use a unique
name
for each file (in this case,name
values ofimage0
,image1
, etc.):for (index, image) in images.enumerated() {
multipartFormData.append(UIImagePNGRepresentation(image)!, withName: "image\(index)", fileName: "image\(index).png", mimeType: "image/png")
}That results in a
$_FILES
of:$_FILES = {
image0 = {
error = 0;
name = "image0.png";
size = 23578;
"tmp_name" = "/tmp/php1bc19G";
type = "image/png";
};
image1 = {
error = 0;
name = "image1.png";
size = 338685;
"tmp_name" = "/tmp/phpcGS5d6";
type = "image/png";
};
};(Ignore the format of this output, but rather just focus on the key/value combinations in this nested directory structure: In terms of what this output is, I had web service send
$_FILES
back as JSON, I then let Alamofire parse it, and this is how the resulting dictionary was output in my client app.)Alternatively, you can use an array for the
name
by including a[]
after the field name, e.g., literallyimage[]
:for (index, image) in images.enumerated() {
multipartFormData.append(UIImagePNGRepresentation(image)!, withName: "image[]", fileName: "image\(index).png", mimeType: "image/png")
}That results in the following to be received on the server:
$_FILES = {
image = {
error = (
0,
0
);
name = (
"image0.png",
"image1.png"
);
size = (
23578,
338685
);
"tmp_name" = (
"/tmp/phpI4XrwU",
"/tmp/php3kVhhl"
);
type = (
"image/png",
"image/png"
);
};
};
It just depends upon how the web service was expecting the request to be created.
uploading multi images to the server with swift using Alamofire or anyway to achieve that from the first step to know how we use it with image picker
finally I got an easy answer using a pod called OpalImagePicker and the way is so easy using Alamofire:
code from the first to understand
import Alamofire
import ImagePicker
import Photos
import OpalImagePicker
class PostVC: UIViewController,UITextViewDelegate,UINavigationControllerDelegate,UIImagePickerControllerDelegate, ImagePickerDelegate,OpalImagePickerControllerDelegate {
var arryOfImages = [UIImage]()
// you have to put them don't worry about those funcs
func wrapperDidPress(_ imagePicker: ImagePickerController, images: [UIImage]) {
print("picked")
}
func doneButtonDidPress(_ imagePicker: ImagePickerController, images: [UIImage]) {
print("done")
func cancelButtonDidPress(_ imagePicker: ImagePickerController) {
print("cancel")
}
// set in your button action to get images the image/video .. etc and num of them
@IBAction func addPicture_clicked(_ sender: Any) {
let imagePicker = OpalImagePickerController()
imagePicker.imagePickerDelegate = self
imagePicker.maximumSelectionsAllowed = 3
imagePicker.allowedMediaTypes = Set([PHAssetMediaType.image]) //you can select only images set this
present(imagePicker, animated: true, completion: nil)
}
func imagePicker(_ picker: OpalImagePickerController, didFinishPickingImages images: [UIImage]){
print(images)
self.arryOfImages = images
picker.dismiss(animated: true, completion: nill
}
The Request You Want
//finally the request and thank you ^^
func addPostClicked(){
guard let text = postTextView.text else {
return
}
let token = "UYJ9ohx_M6JvDbJu0"
let profileId = 104
let params : [String: Any] = [
"postText" :text,
"profileId":profileId
]
Alamofire.upload(
multipartFormData: { multipartFormData in
var count = 1
for img in self.arryOfImages {
//here we send our images
let imageData = img.jpegData(compressionQuality: 0.5)
multipartFormData.append(imageData!, withName: "images[]", fileName: "image\(count).jpeg", mimeType: "image/jpeg")
count += 1
}
for (key, value) in params
{
multipartFormData.append("\(value)".data(using: String.Encoding.utf8)!, withName: key)
}
}, to:"https://api.yoogad.com/rest/api/v1/post/create", method:.post, headers: ["x-auth-token" : token],encodingCompletion: { encodingResult in
switch encodingResult {
case .success(let upload, _, _):
upload.responseJSON { response in
debugPrint(response)
self.dismiss(animated: true)
}
case .failure(let encodingError):
print(encodingError)
}
})
}
Related Topics
Behavior Differences Between Performblock: and Performblockandwait:
Uicollectionview Sticky Header in Swift
Don't Launch Simulator When Running Unittests
Uiwebview Random Crash at [Uiviewanimationstate Release]: Message Sent to Deallocated Instance
Uicollectionview Registerclass: Forcellwithreuseidentifier Method Breaks Uicollectionview
Adding Glow Effect to Uibutton - iOS
Calling Uiviewcontroller Method from App Delegate
Launch Images in iOS 7 with Xcode 5
How to Animate Tab Bar Tab Switch with a Crossdissolve Slide Transition
This Certificate Was Signed by an Unknown Authority
How to Downscale a Uiimage in iOS by the Data Size
Access the Instance of a Viewcontroller from Another in Swift
Rendering PDF in Uiwebview iOS 8, Causes a Black Border Around PDF
Error: Uiview's Window Is Not Equal to Another View's Window