I've a chat view which is designed using UICollectionView. I've successfully implemented image upload functionality where whenever a user clicks an image using image picker the image gets uploaded to the server. Now I'm trying to add progress bar to each image to show the upload status. Currently what I've done is, whenever user picks an image using UIImagePicker my cell gets updated with the latest image and the collection view scrolls to bottom and in the URLsession delegate I catch the last cell and show the progress, but the problem is that, when I pick another image during the upload, the progress bar of both shows on the last cell. Below is my code for image picker and session delegate
func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : AnyObject]) {
let chosenImage = info[UIImagePickerControllerOriginalImage] as! UIImage
selectedImage = chosenImage
//Some other code to update cell data
picker.dismissViewControllerAnimated(true, completion: { () -> Void in
self.scrollToBottomAnimated(true)
})
let qualityOfServiceClass = QOS_CLASS_BACKGROUND
let backgroundQueue = dispatch_get_global_queue(qualityOfServiceClass, 0)
dispatch_async(backgroundQueue, {
print("To run image upload in background")
self.uploadImage(UIImageJPEGRepresentation(self.selectedImage!, 0.5)!, parameters: self.createDictionaryForUploadImageDetails()) { (responseDict, error) -> () in
if (responseDict != nil) {
print(responseDict!)
}
else
{
if error != nil
{
Utilities.showAlertViewMessageAndTitle((error?.localizedDescription)!, title: "Error", delegate: [], cancelButtonTitle: "OK")
}
}
}
})
}
NSURLSession Delegate
func URLSession(session: NSURLSession, task: NSURLSessionTask, didSendBodyData bytesSent: Int64, totalBytesSent: Int64, totalBytesExpectedToSend: Int64)
{
let uploadProgress:Float = Float(totalBytesSent) / Float(totalBytesExpectedToSend)
let section = self.numberOfSectionsInCollectionView(self.chatCollectionView) - 1
let item = self.collectionView(self.chatCollectionView, numberOfItemsInSection:section)-1
let finalIndexPath = NSIndexPath(forItem: item, inSection: section)
if let selectedCell = chatCollectionView.cellForItemAtIndexPath(finalIndexPath)
{
selectedCell.progressView.hidden = false
selectedCell.progressView = Int(uploadProgress * 360)
let progressPercent = Int(uploadProgress*100)
selectedCell.progressView = Int(uploadProgress) == 1
print("Progress-\(progressPercent)% - \(progressView.hidden)")
}
}
How can I get the correct cell for each upload?