1

I want to display images in tableview that are coming in from an API request. I have added the code to fetch the data from API. But my images are not showing in the table view. There is no error. Please help me get the images in the table view.

**Note: var thumbnail in Template service, is the one holding image url.

Below is my code:

    HomeScreenViewController -
    
    class HomeScreenViewController: UIViewController,UITableViewDelegate, UITableViewDataSource, TemplateProtocol {
        
        @IBOutlet weak var templateTableView: UITableView!
    
        var imagearrayForTemplate = [String]()
        var templateCount: Int = 0
        
        override func viewDidLoad() {
            super.viewDidLoad()
            templateTableView.delegate = self
            templateTableView.dataSource = self
            callTemplateService()
        }
        
        func callTemplateService() {
            TemplateService.templateInstance.templateService(APITokenString: "API_Token_Is_passed")
            TemplateService.templateInstance.delegateTemplate = self
            self.templateTableView.reloadData()
        }
        
        func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
            return TemplateService.templateInstance.templateImageArray.count
        }
        
        func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
             let tableCell = tableView.dequeueReusableCell(withIdentifier: "tableViewCell") as? TemplateTableViewCell
            let imagesString = imagearrayForTemplate[indexPath.row]
            tableCell?.templateImages.image = UIImage(named: imagesString)
            return tableCell!
            }
        
        func template() {
            let array = TemplateService.templateInstance.templateImageArray
            for item in array {
                self.imagearrayForTemplate.append(item)
                print("Myarray \(self.imagearrayForTemplate)")
            }
             self.templateTableView.reloadData()
        }
    }
    
    
    Template Service - 
    protocol TemplateProtocol {
        func template()
    }
    
    class TemplateService {
        
        static let templateInstance: TemplateService = TemplateService()
        var templateImageArray: [String] = []
        var delegateTemplate: TemplateProtocol!
    
        func templateService(APITokenString: String) {
            
            let url = URL(string: "Have added API_URL to get the response")
            var request = URLRequest(url: url!)
            request.httpMethod = "GET"
            request.addValue("application/json", forHTTPHeaderField: "Content-Type")
            request.addValue("application/json", forHTTPHeaderField: "Accept")
            request.addValue("Bearer "+APITokenString, forHTTPHeaderField: "Authorization")
            
            let session = URLSession.shared
            session.dataTask(with: request) { (data, response, error) in
                
                if let httpResponse = response as? HTTPURLResponse {
                    print("statusCode: \(httpResponse.statusCode)")
                    print(httpResponse)
                }
                if let data = data {
                    do {
                        guard let json = try JSONSerialization.jsonObject(with: data, options: []) as? [String: Any] else { return }
                        print(json)
                        let template =  TemplateData(json: json)
                        let templateData = template.data
                        for items in templateData  {
                            print(items)
                            for (key,value) in items
                            {
                                if key == "thumbnail"{
                                    print(value)
                                    self.templateImageArray.append(value as! String)
                                }
                            }
                        }
                        DispatchQueue.main.async {
                            self.delegateTemplate.template()
                        }
                    }catch {
                        print(error)
                    }
                }
            }.resume()
        }
    }

TemplateTableViewCell -

class TemplateTableViewCell: UITableViewCell {
    @IBOutlet weak var templateImages: UIImageView!
    
    func configure(url: String) {
        templateImages.image = UIImage(named: url)
    }
}
iosDevSan
  • 65
  • 1
  • 13

1 Answers1

0

UIImage(named: String) tries to load the image locally, You need to download the images. For this purpose, consider using an image downloader like the kingfisher:

imageView.kf.setImage(with: url)

see more: https://github.com/onevcat/Kingfisher

Mohammad Reza
  • 184
  • 2
  • 11
  • 1
    found this link. https://stackoverflow.com/questions/24231680/loading-downloading-image-from-url-on-swift?page=2&tab=votes#tab-top. Used the solution - imageView.image=UIImage(data: NSData(contentsOfURL: NSURL(string: "http://myURL/ios8.png")!)! It worked. just by adding try catch block to the line of code – iosDevSan Jun 07 '21 at 09:49