Vapidant
Vapidant

Reputation: 2682

Reload data in Asynchronous Loading

I have implemented asynchronous image loading into my swift project to load in a series of images in cells in a table.

I have done so with the following extension

extension UIImageView {
public func imageFromServerURL(urlString: String, defaultImage : String?) {
    if let di = defaultImage {
        self.image = UIImage(named: di)
    }

    URLSession.shared.dataTask(with: NSURL(string: urlString)! as URL, completionHandler: { (data, response, error) -> Void in

        if error != nil {
            print(error ?? "error")
            return
        }
        DispatchQueue.main.async(execute: { () -> Void in
            let image = UIImage(data: data!)
            self.image = image

        })

    }).resume()
  }
}

I call the method by declaring an instance method

let imageView = UIImageView()

and then running this in my code later.

cell.posterImageView!.image = UIImage(imageView.imageFromServerURL(urlString: posterImageURL as! String ,defaultImage: "noPosterImage.png" ))

This works mostly except the images don't update in my table until I scroll the image out of view and then scroll it back into view.

After doing my own research I found this method that seems like it could help me

self.tableview.reloadData()

When i tried to implement it into my code like this inside of my extension

DispatchQueue.main.async(execute: { () -> Void in
        let image = UIImage(data: data!)
        self.image = image
        self.tableview.reloadData()
    })

I recieve the error

Value of type 'UIImageView' has no member 'tableview'

I'm new to swift so i'm not quite sure how to fix this error, I'm sure it's something stupidly easy

Any advice on how to either fix this error or simply fix the problem overall?

Upvotes: 0

Views: 76

Answers (1)

Fabian
Fabian

Reputation: 5358

You usually use IBOutlets to connect the views from the storyboard to your UIViewController. In your case you would connect the tableView from the storyboard to the viewController which owns the UIViewController-instance in the starboard.

Then you can call tableView.reload() inside viewController to reload the table.

It is not possible to connect from storyboard to an imageView so you can't connect the tableView to your custom UIImageView class.

Reading on IBOutlets, Storyboards for you to work through.

Upvotes: 1

Related Questions