0

So I have this function which loads Image from the URL and I took it from here

extension UIImageView {

    func loadImageUsingCache(withUrl urlString : String) {

        let url = URL(string: urlString)
        if url == nil {return}
        self.image = nil

        // check cached image
        if let cachedImage = imageCache.object(forKey: urlString as NSString)  {
            self.image = cachedImage
            return
        }

        let activityIndicator: UIActivityIndicatorView = UIActivityIndicatorView.init(style: .medium)
        addSubview(activityIndicator)
        activityIndicator.startAnimating()
        activityIndicator.center = self.center

        // if not, download image from url
        URLSession.shared.dataTask(with: url!, completionHandler: { (data, response, error) in
            if error != nil {
                print(error!)
                return
            }

            DispatchQueue.main.async {
                if let image = UIImage(data: data!) {
                    imageCache.setObject(image, forKey: urlString as NSString)
                    self.image = image
                    activityIndicator.removeFromSuperview()
                }
            }

        }).resume()
    }
}

This works fine for an UIImageView but when I'm trying to load an Image from URL to a UIButton imageview it's not working.

userAvatarButton.imageView!.loadImageUsingCache(withUrl: "https://homepages.cae.wisc.edu/~ece533/images/airplane.png")
OhhhThatVarun
  • 3,981
  • 2
  • 26
  • 49

2 Answers2

0

You can set an image on a button that way. According to apple docs:

When setting the content of a button, you must specify the title, image, and appearance attributes for each state separately.

In other words, you have to specify the image for a specific button state. What you need to do is call UIButton.setImage to set the image.

Rob C
  • 4,877
  • 1
  • 11
  • 24
0

you can try this, i think this will help you.

func imageFromUrl(_ urlString: String) {
        if let url = URL(string: urlString) {
            let request = URLRequest(url: url)
            DispatchQueue.global(qos: .userInitiated).async {
                let imageData = NSData(contentsOf: url)
                DispatchQueue.main.async {
                    if imageData != nil {
                        if let img = UIImage(data: imageData as! Data){
                            DispatchQueue.main.async {
                                self.userAvatarButton.setImage(img, for: .normal)

                            }
                        }
                    } else {
                        print("error")
                    }
                }
            }
        }
    }

And then call like,

imageFromUrl("https://homepages.cae.wisc.edu/~ece533/images/airplane.png")
Vandana pansuria
  • 764
  • 6
  • 14