0

I have heavy code - loading images asynchronously. I am using Grand Central Dispatch, but Activity Indicator does not working. Help me find the error, please

func loadImage() {
    if let imageUrl = NSURL(string: "http://\($url)/1.jpg") {
        let imageRequest: NSURLRequest = NSURLRequest(URL: imageUrl)
        let queue: NSOperationQueue = NSOperationQueue.mainQueue()
        NSURLConnection.sendAsynchronousRequest(imageRequest, queue: queue, completionHandler:{ (response: NSURLResponse!, data: NSData!, error: NSError!) -> Void in
            if data != nil {
                self.image = UIImage(data: data)!
                self.productImageView.image = self.image

            }
        })
    }
}


override func viewDidLoad() {
    super.viewDidLoad()

    self.imageActivityIndicator.startAnimating()
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), { () -> Void in

    self.loadImage()

    dispatch_async(dispatch_get_main_queue(), { () -> Void in
        self.imageActivityIndicator.stopAnimating()
    })
    });


}
Community
  • 1
  • 1
aXXy
  • 358
  • 3
  • 10

1 Answers1

0

it's happening because you are using the imageActivityIndicator in viewDidLoad and the views haven't been added to the main view yet, so if your code would work if you moved it to viewWillAppear function.

Plus you have to hide it when the image finished loading, so this makes your code like this:

func loadImage() {
    if let imageUrl = NSURL(string: "http://skidon.info/1.jpg") {
        let imageRequest: NSURLRequest = NSURLRequest(URL: imageUrl)
        let queue: NSOperationQueue = NSOperationQueue.mainQueue()
        NSURLConnection.sendAsynchronousRequest(imageRequest, queue: queue, completionHandler:{ (response: NSURLResponse!, data: NSData!, error: NSError!) -> Void in
            if data != nil {

                self.image = UIImage(data: data)!
                self.productImageView.image = self.image

                dispatch_async(dispatch_get_main_queue(), { () -> Void in
                    self.imageActivityIndicator.stopAnimating()
                    self.imageActivityIndicator.hidden = true
                })

            }
        })
    }
}


override func viewWillAppear() {
    super.viewWillAppear()

    self.imageActivityIndicator.startAnimating()
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), { () -> Void in

        self.loadImage()

    });


}
Firas
  • 1,742
  • 15
  • 25
  • Thanks! So, now I am using the 'imageActivityIndicator' in 'viewDidLoad' again and fix 'dispatch_async(dispatch_get_main_queue()'. And use **Hides When Stopped** in storyboard. Now it's work! Thanks! – aXXy Aug 09 '15 at 22:24