Swift 4 AlamofireImage with UITableView Cell
Asked Answered
B

10

10

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
    }
Boong answered 21/5, 2018 at 1:42 Comment(5)
Is cell.imageView?.image = image called? Do you have any error logs in console? Is cell.imageView not nil?Bawdy
Did you check if your response is valid or not, by providing a print(response) inside your completion block?Deb
Can you verify that the image urls are valid and the requests are successful. Add some additional logging around this function, check response is valid etcWoolfell
This might looks silly but try to remove corner radius , If you have set any background color set to default , remove any layer operation like shadow , try to toggle clips to bounds , I have the same issue but don't remember exact solution what i did but i did one of aboveBritneybritni
Try any static image as placeholder and check is it showing properly, or user alamofire's imageview's extension imageView.af_setImage( and also print responseBritneybritni
G
2

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.

Giddens answered 21/5, 2018 at 7:14 Comment(4)
Value of type 'UITableViewCell' has no member 'myImage'Boong
'myImage' is the outlet of the UIImageView in UItableviewcell.so here You should write the name of your IBOutlet variable name .Giddens
like, cell.imageView?.image = UIImage(data : imageData!)Giddens
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { return 100.0 } Add this...Giddens
H
4

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

Heffner answered 28/5, 2018 at 7:55 Comment(2)
response.result.value, what kind of this response?Heffner
Alamofire by default calls the response handler on the main dispatch queue, see here. So wrapping the handling in an async closure is not needed, unless responseImage acts differently than the standard response...es. Everything points to an invalid image or URL.Brandtr
G
2

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.

Giddens answered 21/5, 2018 at 7:14 Comment(4)
Value of type 'UITableViewCell' has no member 'myImage'Boong
'myImage' is the outlet of the UIImageView in UItableviewcell.so here You should write the name of your IBOutlet variable name .Giddens
like, cell.imageView?.image = UIImage(data : imageData!)Giddens
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { return 100.0 } Add this...Giddens
D
2

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.
    })
}
Ditzel answered 22/5, 2018 at 5:1 Comment(1)
What result do you get ?Ditzel
I
0

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.

Ina answered 21/5, 2018 at 1:54 Comment(0)
W
0

You need to run this code in the main thread.

DispatchQueue.main.async {
    cell.imageView?.image = image
}
Wolgast answered 21/5, 2018 at 2:29 Comment(0)
A
0

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"))
Ailina answered 21/5, 2018 at 7:30 Comment(2)
I get this error Value of type 'UIImageView' has no member 'sd_setImage'Boong
For that you have to add SDWebImage framework And import the this method will be availableAilina
R
0

your code is correct. i think the transport security block your image over http . add this into your info.plist file

<key>NSAppTransportSecurity</key>
<dict>
    <key>NSAllowsArbitraryLoads</key>
    <true/>
    <key>NSExceptionDomains</key>
    <dict>
        <key>example.com</key>         //put your domain name here
        <dict>
            <key>NSExceptionAllowsInsecureHTTPLoads</key>
            <true/>
            <key>NSIncludesSubdomains</key>
            <true/>
        </dict>
    </dict>
</dict>

and you can also use the alamofire's image library. just add pod alamofireImage.

Rostellum answered 29/5, 2018 at 19:58 Comment(0)
H
0

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
                     }
      }
Holyhead answered 31/5, 2018 at 0:47 Comment(0)
W
0

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)
Wadding answered 1/6, 2018 at 11:39 Comment(0)
E
0

Swift-5 Supported Code That Work Perfectly

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

    let cell = tblView.dequeueReusableCell(withIdentifier: "cell") as! TableViewCell
    cell.lblName.text = arrData[indexPath.row]["name"] as? String

  let imageUrl = arrData[indexPath.row]["imageUrl"] as? String

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

    return cell
} 
Easing answered 13/4, 2019 at 5:26 Comment(2)
use imageUrl as StringEasing
and alamofire request in tableview cellEasing

© 2022 - 2024 — McMap. All rights reserved.