Search code examples
swiftasynchronousactivity-indicatorloadimage

ActivityIndicator in asynchronous - Swift


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()
    })
    });


}

Solution

  • 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()
    
        });
    
    
    }