2

I've been trying to show the progressHUD when my cell loads, and it should show how the download progress are doing. so i placed the code in SDWebimage progress block to get the download progress and pass it into MBProgress HUD to work but i don't know what i am doing wrong here !

let url = NSURL(string: (array[indexPath.row][0] as? String)!)
cell.imageView.sd_setImageWithURL(url, placeholderImage: nil, options: nil, progress: { (value1, value2) -> Void in

    self.HUD = MBProgressHUD(view: self.mycollectionView)
    self.view.addSubview(self.HUD)

    self.HUD.mode = MBProgressHUDMode.AnnularDeterminate
    self.HUD.delegate = self
    self.HUD.show(true)
    var x : Float = Float(value1)
    self.HUD.progress = x

    println(value1)
    println(value2)

    }, completed: block)

I am getting also an error saying : 'MBProgressHUD needs to be accessed on the main thread.'

AaoIi
  • 8,288
  • 6
  • 45
  • 87

3 Answers3

4

I think this enclosure is called on background thread and you need to wrap HUD regarding code in

dispatch_async(dispatch_get_main_queue()) {
         // hud here
    }

as UI changes should be performed on main thread.

And secondly i think the enclosure will be called alot of times (as it is showing progress) and HUD view will be added to subview every time, so you need to take care of that as well.

Usama
  • 1,945
  • 1
  • 13
  • 20
4

You can only update UI from the main thread, just as your error says. Downloading the image is an asynchronous operation that is not performed on the main thread, the callback block therefore can't update the UI - unless you perform the UI updates on the main thread. To do that, you have to use gcd to perform your code on the main thread, try this:

let url = NSURL(string: (array[indexPath.row][0] as? String)!)
cell.imageView.sd_setImageWithURL(url, placeholderImage: nil, options: nil, progress: { (value1, value2) -> Void in

dispatch_async(dispatch_get_main_queue(), {
    self.HUD = MBProgressHUD(view: self.mycollectionView)
    self.view.addSubview(self.HUD)

    self.HUD.mode = MBProgressHUDMode.AnnularDeterminate
    self.HUD.delegate = self
    self.HUD.show(true)
    var x : Float = Float(value1)
    self.HUD.progress = x
})

println(value1)
println(value2)

}, completed: block)
Yannik
  • 2,463
  • 2
  • 16
  • 7
  • Great, now the progress shows but it doesn't calculate any value so the progress can move, its just there ! – AaoIi Aug 21 '15 at 09:52
2

If you are reusing cells then you can add the activity indicator in IB and the then set its class to HUDview or the indicator you want. Then in collectionView cellForItemAtIndexPath method when you create cell add startAnimating method, and then check for completion clousure after assigning image you can stopAnimating.

Parth Adroja
  • 13,198
  • 5
  • 37
  • 71