Swift 4 AlamofireImage with UITableView Cell

2019-04-21 01:31发布

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 and detailTextLabel

override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

        let cell = tableView.dequeueReusableCell(withIdentifier: "trendingCell", for: indexPath)

        print(self.array[indexPath.row])

        cell.textLabel?.text = (self.array[indexPath.row]["title"] as! String)

        cell.detailTextLabel?.text = (self.array[indexPath.row]["username"] as! String)

        Alamofire.request("http://xxxxxxx.com/uploads/" + (self.array[indexPath.row]["cover"] as! String)).responseImage { response in
            if let image = response.result.value {
                cell.imageView?.image = image
            }
        }

        return cell
    }

10条回答
家丑人穷心不美
2楼-- · 2019-04-21 01:49

First you have to check , have you got the proper response if you got the reasponse than write the code like

Alamofire.request(imageUrl!, method: .get).response { response in

                           if let image = UIImage(data: response.data!) {
                          cell. imageView?.image = image
                     }
      }
查看更多
Animai°情兽
3楼-- · 2019-04-21 01:49

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.

查看更多
forever°为你锁心
4楼-- · 2019-04-21 01:52

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"))
查看更多
老娘就宠你
5楼-- · 2019-04-21 01:53

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)
查看更多
冷血范
6楼-- · 2019-04-21 01:58

Try this:

 Alamofire.request(imageUrl!, method: .get).response { response in
                    guard let image = UIImage(data:response.data!) else {
                        // Handle error
                        return
                    }
                    let imageData = UIImageJPEGRepresentation(image,1.0)
                    cell.myImage.image = UIImage(data : imageData!)
                }

This works fine for me.. Hope This will helpful.

查看更多
放我归山
7楼-- · 2019-04-21 02:01

Of course your image will not show for you. Cause when Alamofire starts downloading your image its process in background thread. But you are working in Main Thread or UI Thread so you need to swap from background to Main Thread it will work for you.

Alamofire.request("http://xxxxxxx.com/uploads/" + (self.array[indexPath.row]["cover"] as! String)).responseImage { response in
       DispatchQueue.main.async {
            if let image = response.result.value {
                cell.imageView?.image = image
            }
        }
}

If you think it is difficulty for you to do this i recommend you to use this library called Kingfisher it will handle asynchronous loading images for you that make your cell's table run in smoothly.

Link: https://github.com/onevcat/Kingfisher

查看更多
登录 后发表回答