【发布时间】: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