【问题标题】:tableview is not loading sometimes , is there anyway to refresh it?tableview 有时不加载,有没有刷新它?
【发布时间】:2021-03-24 14:20:11
【问题描述】:

我是 swift 的新手,已经实现了一个带有 url 会话数据的 tableview,它工作正常,除了图像没有加载,有时数据来晚并且 tableview 是空的。
我输入了 http://localhost:3000/nameofimage.png ,我得到了我的图像,但是在 tableview 中它不起作用

import UIKit
import Kingfisher

class BikelistViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {
   

    var bikes =  [Bike]()
    
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return bikes.count
    }
    
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "mCellBike")
        let contentView = cell?.contentView
        let imageView = contentView?.viewWithTag(1) as! UIImageView
        let label = contentView?.viewWithTag(2) as! UILabel
        DispatchQueue.main.async {
            
            label.text = self.bikes[indexPath.row].model
            let url = URL(string: "http://localhost:3000/"+self.bikes[indexPath.row].image)
            imageView.kf.setImage(with: url)
       
        }
       
        return cell!
    }
   
    

    //passage de parametres entre les controleurs
        //cell OnclickListener
        
         func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
            let bike = bikes[indexPath.row]
            performSegue(withIdentifier: "mBikeDetails" , sender: bike) //passage de variable locale)
            
        }
        
        /* prepare est pour passer les parametres  */
        override func prepare(for segue: UIStoryboardSegue, sender: Any?){
        
        if segue.identifier == "mBikeDetails" {
        
        let bike = sender as! Bike
        let destination = segue.destination as! BikeDetailsViewController
            destination.id = bike.bike_id
            destination.model = bike.model
            destination.type = bike.type
            destination.mprice = bike.price
            destination.image = bike.image
            
        
        }}
    


    override func viewDidLoad() {
        super.viewDidLoad()

        //get
      
       guard let url = URL(string: "http://localhost:3000/bikes") else {
       return
       }
       let session = URLSession.shared
       session.dataTask(with: url)  { ( data , response ,error) in
           if let response = response {
               print(response)
           }
           
           if let data = data {
               print(data)
               do
               {
                let json = try JSONSerialization.jsonObject(with: data, options: []) as! [[String:Any]]
                self.bikes.removeAll()
                
                for item in json {
                    let id = item["bike_id"] as! Int
                    let model = item["model"] as! String
                    let type = item["type"] as! String
                    let price = item["price"] as! String
                    let image = item["image"] as! String
                    self.bikes.append(Bike(id: id,model: model,type: type,price: price,image: image))
                }
                for item in self.bikes {
                    print(item.image)
                    print("http://localhost:3000/"+item.image)
                    
                }
                print(self.bikes)
               }catch{
                   print(error)
               }
            
           }
           
       }.resume()
       
        
        // Do any additional setup after loading the view.
    }
    


}
 

我试图让我的图像加载到我的 tableview 中,我的数据显示除了我的图像。有时数据来晚了,tableview 是空的 我在这里有什么遗漏吗?

【问题讨论】:

  • 是的,我解决了这个问题

标签: ios swift xcode uitableview urlsession


【解决方案1】:

您正试图在主线程中获取数据,这就是它滞后的原因。让主线程创建单元对象,不要在这里实现任何网络操作,所以这在您的代码中是错误的:

imageView.image = UIImage(named: "http://localhost:3000/"+bikes[indexPath.row].image)

您不应在主线程中执行网络操作。如果您愿意,您可以使用第三方库,例如 KingFisher 或直接使用您的资产文件夹。如果你这样做,你的 tableview 将会放松:

imageView.image = UIImage(named: "happy_bikeimage_coming_from_assets_folder")

例如获取数据背景:

DispatchQueue.global(qos: .userInitiated).async {
    if let url = URL(string: urlString) {
        if let data = try? Data(contentsOf: url) {
            self.parse(json: data)
            return
        }
    }
}

【讨论】:

  • 我应该从哪里获取数据?请准确地告诉我,我是一个真正的 swift 初学者
  • 所以我应该把 DispactchQueue 放在哪个方法中?
【解决方案2】:

如果您在线加载图像,您可以使用 kingFisher,请检查: https://stackoverflow.com/a/65114085/14437411

或者你可以在你的资产文件夹中使用它并正常地用它的名字来调用图像:

DispatchQueue.main.async {
     UIImage(named: "imageName.extension")
}
   

【讨论】:

  • 所以我应该在 func tableview 中替换 mageView.image = UIImage (named: "localhost:3000/"+bikes[indexPath.row].image) ??? DispatchQueue.main.async { UIImage(named: "imageName.extension") }
  • 是的,你可以试试,可能更快
  • 你认为我也应该把 label.text = bikes[indexPath.row].model 放在里面吗?因为它也是一个后台任务
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2016-03-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-07-31
相关资源
最近更新 更多