Swift 4 AlamofireImage with UITableView Cell

后端 未结 10 3300
梦如初夏
梦如初夏 2021-02-20 12:56

I am using AlamofireImages to try to download an image from a server and display it in my table view cell, this is what I got, but my images does not appear, just the textLabel

相关标签:
10条回答
  • 2021-02-20 13:53

    This helped me:

    Create this function first to help pull down the image. If you're pulling multiple images, you may want to create a new swift file and make this static or just call it in the file that you need it. This way you can refer to it instead of re-writing code:

    static func loadImage(_ imageView: UIImageView,_ urlString: String) {
        let imgURL: URL = URL(string: urlString)!
        URLSession.shared.dataTask(with: imgURL) { (data, respond, error) in
            guard let data = data, error == nil else { return}
    
            DispatchQueue.main.async (execute: {
                imageView.image = UIImage(data: data)  
            })
        }.resume()
    }
    

    Then to pull down the info:

    if let logoName = variable.logo {
            StaticFileName.loadImage(cell.imgVariableInCell, "\(logoName)")
        }
        return cell
    }
    

    Then you're good to go.

    0 讨论(0)
  • 2021-02-20 13:55

    You should pass the link as a variable to a variable in the cell and override the awakefromnib function in UITableViewCell. Inside the awakeFrom nib you call the alamofire request to load the image in the cell, with this way you will not call the query every time it reuses the cell.

    so

    //CellCode

    import Alamofire
    ...
    
        var imageLink:String?
    
        override func awakeFromNib() {
                super.awakeFromNib()
        Alamofire.request(imageLink).responseImage { response in
                    if let image = response.result.value {
                        self.imageView?.image = image
                    }
                }
        }
    
    
    //cell configuration
    cell.imageLink = "http://xxxxxxx.com/uploads/" + self.array[indexPath.row]["cover"] as! String)
    
    0 讨论(0)
  • 2021-02-20 13:56

    Using AlamofireImages

    if let url = URL(string: "your url") {
    
        cell.imageView?.af_setImage(withURL:url, placeholderImage: nil, filter: nil,  imageTransition: .crossDissolve(0.2), runImageTransitionIfCached: false, completion: {response in
          // do stuff when is downloaded completely.
        })
    }
    
    0 讨论(0)
  • 2021-02-20 14:03

    You can use SDWebImage

    First You need to Import this

    import SDWebImage
    

    Then You may use this method

    let imgUrl = URL(string:"your image URL string")
    cell.imageView?.sd_setImage(with: imgUrl, placeholderImage: UIImage(named: "propic"))
    
    0 讨论(0)
提交回复
热议问题