Search code examples
iosswiftuibuttonuiimageview

How to load Image into UIButton Swift From HTTP Request


I have been getting images from my API and in the past I have loaded them into a UIImage with the extension you will see below. However, now I am trying to get the images from the API and load them into UIButton image views. I don't know what to do to the extension and the other code to make it work. I appreciate the help!

Extension

Extension UIImageView {
func getURL2(url: URL, contentMode mode: UIViewContentMode = .scaleAspectFit) {
    contentMode = mode
    URLSession.shared.dataTask(with: url) { data, response, error in
        guard
            let httpURLResponse = response as? HTTPURLResponse, httpURLResponse.statusCode == 200,
            let mimeType = response?.mimeType, mimeType.hasPrefix("image"),
            let data = data, error == nil,
            let image = UIImage(data: data),
            httpURLResponse.url == url
            else { return }
        DispatchQueue.main.async() {
            self.image = image
        }
        }.resume()
}

func downloadedFrom2(link: String, contentMode mode: UIViewContentMode = .scaleAspectFit) {
    guard let url = URL(string: link) else { return }
    getURL2(url: url, contentMode: mode)

    }
}

Other code

func loadProfilePhoto(image: UIButton, link: String) {
    image.downloadedFrom2(link: link)
    image.imageView!.clipsToBounds = true
    image.imageView!.layer.cornerRadius = (image.imageView!.frame.height) / 2
    image.imageView!.contentMode = .scaleAspectFill
}

func loadRandom8() {
    if self.users.count == 8 {
        let completelink1 = users[0].picture_url
        //ex. https://api.adorable.io/avatars/200/AngelicAlling.png
        let completelink2 = users[1].picture_url
        let completelink3 = users[2].picture_url
        let completelink4 = users[3].picture_url
        let completelink5 = users[4].picture_url
        let completelink6 = users[5].picture_url
        let completelink7 = users[6].picture_url
        let completelink8 = users[7].picture_url

        loadProfilePhoto(image: p2Image, link: completelink1)
        loadProfilePhoto(image: p2Image, link: completelink2)
        loadProfilePhoto(image: p3Image, link: completelink3)
        loadProfilePhoto(image: p4Image, link: completelink4)
        loadProfilePhoto(image: p5Image, link: completelink5)
        loadProfilePhoto(image: p6Image, link: completelink6)
        loadProfilePhoto(image: p7Image, link: completelink7)
        loadProfilePhoto(image: p8Image, link: completelink8)

Solution

  • Your current extension is for UIImageView but you want to load the image in a UIButton, so change the extension to UIButton and make sure the button's type is set to Custom and not System. You can do this from the storyboard.

    extension UIButton {
      func getURL2(url: URL, contentMode mode: UIViewContentMode = .scaleAspectFit) {
        contentMode = mode
        URLSession.shared.dataTask(with: url) { data, response, error in
          guard
            let httpURLResponse = response as? HTTPURLResponse, httpURLResponse.statusCode == 200,
            let mimeType = response?.mimeType, mimeType.hasPrefix("image"),
            let data = data, error == nil,
            let image = UIImage(data: data),
            httpURLResponse.url == url
            else { return }
          DispatchQueue.main.async() {
            self.setImage(image, for: .normal)
            self.imageView?.contentMode = mode
          }
          }.resume()
      }
      
      public func downloadedFrom2(link: String, contentMode mode: UIViewContentMode = .scaleAspectFit) {
        guard let url = URL(string: link) else { return }
        getURL2(url: url, contentMode: mode)
        
      }
    }
    

    If it didn't work for you read this