swift how to set button image from api

Viewed 122

I'm trying to set an image on the button from API here my code is

    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "Cell", for: indexPath) as! CreatGroupCollectionViewCell
        cell.btn2.setImage(downloaded(link: String), for: .normal)
        return cell
    }

I also use an extension to download an image from the link

extension UIImageView {
    func downloaded(from 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)
                else { return }
            DispatchQueue.main.async() { [weak self] in
                self?.image = image
            }
            }.resume()
    }
    func downloaded(from link: String, contentMode mode: UIViewContentMode = .scaleAspectFit) {
        guard let url = URL(string: link) else { return }
        downloaded(from: url, contentMode: mode)
    }
}

please tell me how to set an image on the button

2 Answers
Try using this extension to set image from url in a UIButton:

    extension UIButton {
      func setImageFrom(url link: String) {
          guard let url = URL(string: link) else { return }
          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)
              else { return }
              DispatchQueue.main.async() { [weak self] in
                  self?.setImage(image, for: .normal)
              }
          }.resume()
       }
    }

Use this extension to load image from url and store it to cache for faster reload.

let imageCache = NSCache<AnyObject, AnyObject>()

extension UIImageView {
func loadImageUsingCacheWithUrlString(_ urlString: String) {
    self.image = nil
    //check cache for image first
    if let cachedImage = imageCache.object(forKey: urlString as AnyObject) as? UIImage {
        self.image = cachedImage
        return
    }
    //otherwise fire off a new download
    guard let url = URL(string: "\(urlString)") else { return }
    URLSession.shared.dataTask(with: url, completionHandler: { (data, response, error) in
        //download hit an error so lets return out
        if error != nil {
            print(error ?? "")
            return
        }
        DispatchQueue.main.async(execute: {
            if let downloadedImage = UIImage(data: data!) {
                imageCache.setObject(downloadedImage, forKey: urlString as AnyObject)
                self.image = downloadedImage
            }
        })
    }).resume()
}

}
Related