I have a collectionView cell which has five imageviews. I am using the following the answer given by javimuu to load images in the background. Link
It works well and all the images load in the correct imageview. But it is very slow process and the images load in random order. I am having difficulty in showing the activity indicator and hiding it when all the images are done loading for a specific cell i.e, Keep showing indicator while images are loading and hide it when all 5 images are loaded.
Please help.
Update:
func downloadImageFromLink(link:NSURL,group: dispatch_group_t, completion:(isDone: Bool) -> Void) {
self.image = nil
imageURL = link.absoluteString
dispatch_group_enter(group)
NSURLSession.sharedSession().dataTaskWithURL(link, completionHandler: {
(data, response, error) -> Void in
if error != nil {
print(error)
return
}
if let imageFromCache = imageCache.objectForKey(link.absoluteString) as? UIImage {
self.image = imageFromCache
dispatch_group_leave(group)
return
}
dispatch_async(dispatch_get_main_queue(),{
let imageToCache = UIImage(data: data!)
if self.imageURL == link.absoluteString {
self.image = imageToCache
imageCache.setObject(imageToCache!, forKey: link.absoluteString)
}
dispatch_group_leave(group)
})
}).resume()
}
func loadImagesInCell(cell: WatchFaceCell, images:NSArray ,completion:() ->Void) {
self.startAnimating(cell.contentView)
let group: dispatch_group_t = dispatch_group_create()
for model in images{
if model is WFCreatorModel {
let wfModel: WFCreatorModel = model as! WFCreatorModel
switch wfModel.imageType {
case .Dial:
cell.dialImage.downloadImageFromLink(wfModel.imageURL,group: group, completion: { (isDone) in
})
case .HourHand:
cell.hourHandImage.downloadImageFromLink(wfModel.imageURL,group: group, completion: { (isDone) in
})
case .MinuteHand:
cell.minuteHandImage.downloadImageFromLink(wfModel.imageURL,group: group, completion: { (isDone) in
})
case .SecondHand:
cell.secondHandImage.downloadImageFromLink(wfModel.imageURL,group: group, completion: { (isDone) in
})
case .Notification:
cell.notificationImage.downloadImageFromLink(wfModel.imageURL, group: group,completion: { (isDone) in
})
}//end of switch
}//end of if else
}//end of for
dispatch_group_notify(group, dispatch_get_main_queue()) {
self.stopAnimating(cell.contentView)
completion()
}
}