Multiple Images Upload Handler For iOS (Swift)

Vishal Jadav
Mac O’Clock
Published in
3 min readSep 27, 2020

For handling upload multiple files and for events like cancel request , pause and resume upload we would handle it through file upload manager array. There would be array of files let’s say images. we would handle it through multiple files upload manager for each image in the list. I have used alamofire for this upload process.

Here is UploadManager Class Implementation :

import Foundation
import UIKit
class FileUploadManager : NSObject {// MARK : Variables Declarationvar id: String?var imgData : Data?var image: UIImage?var progress: Double? { didSet { DispatchQueue.main.async { self.progressBlock?(self.progress) } }}var uploadStatus: FileUploadStatus = .notStartedvar progressBlock: ((Double?)->())?private weak var uploadTask: UploadRequest?
// MARK : Data Init Implementation
convenience init(id: String ,imgData: Data ,img: UIImage) { self.init() self.id = id self.imgData = imgData self.image = img}private override init() {}
func pauseTask(){ self.uploadStatus = .pause self.uploadTask?.suspend()}func resume(){ self.uploadStatus = .uploading self.uploadTask?.resume()}func cancelUpload() { self.uploadStatus = .failed self.uploadTask?.cancel()}
func uploadImgFile(mimeType:String = "image/png",fileName:String = "\(UUID().uuidString).png", request: ((URLSessionUploadTask?)->())? = nil, completionHandler: @escaping (MultiImgFileUpload , [String:Any]?, Error?, APIStatus) -> Void) {if let galleyImgData = imgData { self.uploadStatus = .uploadingDispatchQueue.global(qos: .background).async { let headersData : HTTPHeaders = [ "API-KEY": "", ]self.uploadTask = AF.upload(multipartFormData: { multiPart inmultiPart.append(galleyImgData, withName: "", fileName:fileName, mimeType: mimeType)}, to: URLHelper.uploadImg, method: .post, headers: headersData) .uploadProgress(queue: .main, closure: { progress in self.uploadStatus = .uploading self.progressBlock?(progress.fractionCompleted)}).responseJSON(completionHandler: { data in print("Upload finished: \(data)")}).response { (response) inswitch response.result {case .success(let result): if let getdata = result{ do { if let jsonResponse = try JSONSerialization.jsonObject(with: getdata, options : .allowFragments) as? [String:Any] { self.uploadStatus = .uploaded completionHandler(self, jsonResponse, nil, .success) }} catch let error as NSError { print(error) }}case .failure(let err): self.uploadStatus = .failed completionHandler(self, nil, err, .failure) } } } } }}

Now let’s say we have array of images to be displayed in tableview and we want to upload them then we could upload them as below implementation. Through that you can upload multiple images, track progress and get status of completion through our completion handler. In tableview select method you could pause and resume operations as mentioned below.

// MARK : Images Upload Array Declarationvar ImgsUploadArr = [FileUploadManager]()
// MARK : UITableview DataSource, Delegate Methods Implementation
extension ImgUploadHandlerVC : UITableViewDataSource,UITableViewDelegate{func numberOfSections(in tableView: UITableView) -> Int { return 1}func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return self.ImgsUploadArr.count}func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "ImgUploadTableviewCell", for: indexPath) as! ImgUploadTableviewCell if self.ImgsUploadArr.count > 0 { let fileUpload = self.ImgsUploadArr[indexPath.row] fileUpload.progressBlock = { (pro) in cell.imgProgressView.progress = Float(pro ?? 0.0) } fileUpload.uploadImgFile { (fileUploadGet, response, error, status) inDispatchQueue.main.async { if status == .success{ // MARK : Handle Response } } } } return cell
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { let cell = tableView.cellForRow(at: indexPath) as! ImgUploadTableviewCelllet fileUpload = self.ImgsUploadArr[indexPath.row]if fileUpload.uploadStatus == .uploading { fileUpload.pauseTask() cell.playPauseButton.setImage( imageLiteral(resourceName: "resume"), for: .normal)}else if fileUpload.uploadStatus == .pause { fileUpload.resume() cell.playPauseButton.setImage( imageLiteral(resourceName: "pause"), for: .normal) } }}

Thank You For Reading :)

--

--