Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Display Activity Indicator in tableview cell

I'm loading different images in a basic tableview cell and would like to show the activity indicator in the cell while the image is loading. I'm using a separate cell file like sample code. I know where to place the code just not exactly sure about the syntax. I've found a few ways to put code into a view but not specifically in a cell. Anyone have an idea? Thanks.

func configureCell(favorite: Article) {
    self.favorite = favorite

    downloadImage(NSURL(string: self.favorite.mainImage)!)

func downloadImage(url: NSURL, type: String) {
    getDataFromUrl(url) { (data, response, error) in
        //show activity indicator
        dispatch_async(dispatch_get_main_queue()) { () -> Void in
            guard let data = data where error == nil else { return }
                self.mainImage.image = UIImage(data: data)
        }
    }
}

func getDataFromUrl(url: NSURL, completion: ((data: NSData?, response: NSURLResponse?, error: NSError?) -> Void)) {

    NSURLSession.sharedSession().dataTaskWithURL(url) { (data, response, error) in
        completion(data: data, response: response, error: error)
    }.resume()

}
like image 907
Keith Avatar asked Apr 14 '26 08:04

Keith


1 Answers

You could do like below, let me know if that works for you, you can modify the frame as per your requirement.

func downloadImage(url: NSURL, type: String) {
    let activityIndicator = UIActivityIndicatorView()
    activityIndicator.frame = self.mainImage.bounds

    getDataFromUrl(url) { (data, response, error) in
        //show activity indicator
        self.mainImage.addSubview(activityIndicator)
        activityIndicator.startAnimating()
        dispatch_async(dispatch_get_main_queue()) { () -> Void in
            guard let data = data where error == nil else { return }
            activityIndicator.stopAnimating()
            activityIndicator.removeFromSuperview()
            self.mainImage.image = UIImage(data: data)
        }
    }
}
like image 51
Santosh Avatar answered Apr 16 '26 22:04

Santosh



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!