首页 > 解决方案 > 在 tableview 中显示图像,这些图像是在 swift 中作为 URL 响应 api 获取的

问题描述

我想在表格视图中显示来自 API 请求的图像。我添加了从 API 获取数据的代码。但是我的图像没有显示在表格视图中。没有错误。请帮我在表格视图中获取图像。

**注:模板服务中的var thumbnail,是一个保存图片url。

下面是我的代码:

    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)
    }
}

标签: swiftimageapiurltableview

解决方案


UIImage(named: String) 尝试在本地加载图像,您需要下载图像。为此,请考虑使用像翠鸟这样的图像下载器:

imageView.kf.setImage(with: url)

查看更多:https ://github.com/onevcat/Kingfisher


推荐阅读