Zafar Ahmad
Zafar Ahmad

Reputation: 3219

Start animating UIActivityIndicator when image downloads throug contentsOfURL synchronous

I am trying to show UIActivityIndicator when images start downloading, and it animate until all images are downloads. But UIActivityIndicator not animate, it animate when all images are downloads. I've found that contentsOfURL is synchronous method and blocks the main thread. I want to use contentsOfURL for downloading images. Anyone have any idea how i can animate UIActivityIndicator when images start downloading? Thanks

var indeX = 0  
var imageArrayNsData : [NSData] = []
var posts = NSMutableArray()

myActivityIndicator.startAnimating()
self.view.addSubview(myActivityIndicator)
self.view.userInteractionEnabled = false

for _ in posts.valueForKey("enclosure") as! [NSString]{
    let picURL = self.posts.objectAtIndex(indeX).valueForKey("enclosure") as! String
    let url = NSURL(string: picURL)
    let data = NSData(contentsOfURL: url!)
    let IMG = UIImage(data: data!)
    let dtA : NSData = NSData(data: UIImagePNGRepresentation(IMG!)!)
    print("download")
    imageArrayNsData.append(dtA)
    indeX++
    print(indeX)
}                   
self.view.userInteractionEnabled = true
myActivityIndicator.stopAnimating()

Upvotes: 0

Views: 112

Answers (1)

Zac Kwan
Zac Kwan

Reputation: 5747

To do it Asynchronously, you will have to use dispatch. Infact, AlamofireImage uses dispatch to handle it as well.

In my opinion, you could have your code in a dispatch for queue user initial and update the main queue when completed for the myActivityIndicator and self.view.userInteractionEnabled

dispatch_async(dispatch_get_global_queue(Int(QOS_CLASS_USER_INITIATED.rawValue), 0)) { 
  //your download code here

  dispatch_async(dispatch_get_main_queue()) {
    self.view.userInteractionEnabled = true
    myActivityIndicator.stopAnimating()
   }  
}

Upvotes: 1

Related Questions