Search code examples
iosswiftalamofire

Swift 4 proper way to display images from api in UITableView


I am using UITableViewController to display a list of items from a web service and these items have images and I using AlamofireImage to get the data from image and display them in UITableViewCell like so:

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

        let cell = tableView.dequeueReusableCell(withIdentifier: "postsCell", for: indexPath) as! PostsCell

        let imgUrl = URL(string:"http://example.com/uploads/" + (self.array[indexPath.row]["cover"] as! String))

        cell.delegate = self

        Alamofire.request(imgUrl!).responseImage { response in
            DispatchQueue.main.async {
                if let image = response.result.value {
                    cell.message?.text = (self.array[indexPath.row]["title"] as! String)
                    cell.subMessage?.text = (self.array[indexPath.row]["username"] as! String)
                    cell.profileImage?.image = image

                }
            }
        }

        return cell
    }

and here is how I am populating self.array

getPosts(username: self.username!) { result in

            self.array = result
            self.tableView.reloadData()

        }

Here is getPosts:

func getPosts(username: String, completionHandler:@escaping (_ result:Array<Dictionary<String, Any>>) -> Void)
    {
        var returnedResults = Array<Dictionary<String, Any>>()

        APIController().getUsersPosts(username: username)
        {
            (result: Array<Dictionary<String, Any>>) in

            DispatchQueue.main.async {

                //Return our results

                returnedResults = result
                completionHandler(returnedResults)

            }
        }
    }

and here is my call to my api

func getPosts(username: String, completion: @escaping (_ result: Array<Dictionary<String, Any>>) -> Void)
    {

        let parameters: Parameters = [
            "username": username
        ]

        Alamofire.request(webservice + "?action=posts", method: HTTPMethod.post, parameters: parameters, encoding: URLEncoding.httpBody, headers: [:]).responseJSON { response in

            if(response.error == nil)
            {
                if let result = response.result.value {

                    let jsonData = result as! Array<Dictionary<String, Any>>

                    completion(jsonData)

                }
            }

        }
    }

My question is, is there a better and more efficient way of displaying images from a URL?


Solution

  • You can use SDWebImage which maintains cache of images for your app,

    You can use it in following manner:

    import SDWebImage
    
    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "postsCell", for: indexPath) as! PostsCell
    
        let imgUrl = URL(string:"http://example.com/uploads/" + (self.array[indexPath.row]["cover"] as! String))
    
        cell.profileImage.sd_setImage(with: imgUrl, placeholderImage: UIImage(named: "placeholder.png"))
    
        // REST OF YOUR CODE TO FILL OTHE DATA OF YOUR CELL
        return cell
    }
    

    You can refer below git link for more information: https://github.com/rs/SDWebImage