1

I have been trying to add asynchronous loading into a project i've been working on. I have been working off some code in another StackOverFlow question.

I added the follow 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()
   }
 }

and I am trying to call the method like this

posterImageURL = UIImageView.imageFromServerURL("http://image.tmdb.org/t/p/w185/" + posterImageFilename)

I am being returned the following error

Instance member 'imageFromServerURL' cannot be used on type 'UIImageView'; did you mean to use a value of this type instead?

I am new to swift. It sounds to me like it's not reading the extension at all. Without the call to the method the code itself builds properly.

The extension is located right below my import statements as when I put it inside the class I recieved the error

Declaration is only valid at file scope

Vapidant
  • 2,532
  • 2
  • 12
  • 26

1 Answers1

3

This is an instance method, not a class one. You have to create an instance of type UIImageView first and then call the method. Example:

let imageView = UIImageView() imageView.imageFromServerURL("http://image.tmdb.org/t/p/w185/"+posterImageFilename)

Linh Ta
  • 593
  • 6
  • 11