tableview 是空的,但我看到操场上的数据来自 urlsession
Posted
技术标签:
【中文标题】tableview 是空的,但我看到操场上的数据来自 urlsession【英文标题】:tableview is empty but I see the data in playground coming from urlsession 【发布时间】:2020-12-14 16:12:09 【问题描述】:我是 swift 的初学者,我使用 url session 通过 post 请求填充我的 tableview,我在操场上看到数据但我发现 tableview 是空的,我不知道为什么,但我使用的模型是 Rent 和 Rent
租用模型:
import Foundation
class Rent
var location_id: Int
var datelocation:String
var adresselocation: String
var user_id: Int
var bike_id: Int
var model: String
var type: String
var price: String
var image: String
init(id: Int ,date: String , adresse: String , user: Int , bike: Int , model: String ,type:String ,price:String ,image:String )
self.location_id = id
self.datelocation = date
self.adresselocation = adresse
self.model = model
self.user_id = user
self.bike_id = bike
self.type = type
self.price = price
self.image = image
我还使用了另一个模型 Rents:
import Foundation
class Rents: Codable
var location_id: Int
var datelocation:String
var adresselocation: String
var user_id: Int
var bike_id: Int
var model: String
var type: String
var price: String
var image: String
我的 urlsession 是后查询,但我检索了我的 tableview 所需的所有数据
这是我的表格视图代码:
import UIKit
import CoreData
class rentlistViewController: UIViewController , UITableViewDataSource, UITableViewDelegate
var u = ConnectedUser()
var rents = [Rent]()
override func viewDidLoad()
super.viewDidLoad()
// Do any additional setup after loading the view.
self.DisplayConnectedUser()
/*DispatchQueue.main.async
self.getRents()
*/
//post
guard let url = URL(string: "http://localhost:3000/locations") else
return
let bodyparameters = [ "user_id": self.u.user_id! , "name": self.u.name! , "lastname": self.u.lastname! , "email": self.u.email! , "password": self.u.password! , "phone": self.u.phone! ] as [String : Any]
print(bodyparameters)
var request = URLRequest(url: url)
request.httpMethod = "POST"
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
guard let httpBody = try? JSONSerialization.data(withJSONObject: bodyparameters, options: []) else
print("error in sending data")
return
request.httpBody = httpBody
let session = URLSession.shared
session.dataTask(with: request) (data,response,error) in
if let response = response
print(response)
if let data = data
do
//let json = try JSONSerialization.jsonObject(with: data, options: [])
// print(json);
print(data)
let rt = try JSONDecoder().decode([Rents].self, from: data)
print(rt)
for item in rt
let id = item.location_id
let adresselocation = item.adresselocation
let datelocation = item.datelocation
let user = item.user_id
let bike = item.bike_id
let model = item.model
let type = item.type
let price = item.price
let image = item.image
self.rents.append(Rent(id: id ,date: datelocation, adresse: adresselocation,user: user, bike: bike, model: model , type: type , price: price, image: image))
for item in self.rents
print(item.location_id)
print(item.adresselocation)
print(item.datelocation)
print(item.user_id)
print(item.bike_id)
print(item.model)
print(item.type)
print(item.price)
print(item.image)
print(self.rents)
catch
print("error in parsing")
print(error)
.resume()
func DisplayConnectedUser()
let appDelegate = UIApplication.shared.delegate as! AppDelegate
//represente l'ORM
let persistentContainer = appDelegate.persistentContainer
let managedContext = persistentContainer.viewContext //retourne NSManagedObject toujours
//la requete retourne un NSManagedObject
let request = NSFetchRequest<NSManagedObject>(entityName : "Users")
//execution de la requete
do
let result = try managedContext.fetch(request)
for item in result
print(item.value(forKey: "user_id") as! Int )
print(item.value(forKey: "email") as! String)
self.u.user_id = (item.value(forKey: "user_id") as! Int)
self.u.email = (item.value(forKey: "email") as! String)
self.u.password = (item.value(forKey: "password") as! String)
self.u.name = (item.value(forKey: "name") as! String)
self.u.lastname = (item.value(forKey: "lastname") as! String)
self.u.phone = (item.value(forKey: "phone") as! String)
print(self.u.user_id!)
print(self.u.email!)
print(self.u.password!)
print(self.u.name!)
print(self.u.lastname!)
print(self.u.phone!)
catch
print("NO DATA FOUND , Error")
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int
return rents.count
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell
let cell = tableView.dequeueReusableCell(withIdentifier: "cellRent")
let contentView = cell?.contentView
let label = contentView?.viewWithTag(1) as! UILabel
DispatchQueue.main.async
label.text = self.rents[indexPath.row].model
print("heloooooo"+label.text!)
return cell!
//passage de parametres entre les controleurs
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath)
let rent = self.rents[indexPath.row]
performSegue(withIdentifier: "mRentDetails" , sender: rent) //passage de variable locale)
/* prepare est pour passer les parametres */
override func prepare(for segue: UIStoryboardSegue, sender: Any?)
if segue.identifier == "mRentDetails"
let rent = sender as! Rent
let destination = segue.destination as! RentDetailsViewController
destination.datelocation = rent.datelocation
// destination.hours = rent
// destination.totalprice = rent
destination.bikemodel = rent.model
destination.biketype = rent.type
destination.priceperhour = rent.price
我的问题是为什么如果我在操场上的数据显示完全正确,为什么它没有显示在我的 tableview 中?
我的工作出了什么问题???有没有办法让结果显示在我的表格视图中?我的 tableview 接收数据晚了吗?还是我的模型类有问题???
这里我需要证明我的请求正常工作:
["email": "faresbenslama95@gmail.com", "password": "123456", "user_id": 10, "phone": "12345671", "name": "benslama", "lastname": "fares"]
<NSHTTPURLResponse: 0x600003848120> URL: http://localhost:3000/locations Status Code: 200, Headers
Connection = (
"keep-alive"
);
"Content-Length" = (
339
);
"Content-Type" = (
"text/html; charset=utf-8"
);
Date = (
"Mon, 14 Dec 2020 15:50:11 GMT"
);
Etag = (
"W/\"153-s80IUuqdLC0Rkz3oIqCM7x8xP7I\""
);
"Keep-Alive" = (
"timeout=5"
);
"X-Powered-By" = (
Express
);
339 bytes
[Bicycall.Rents, Bicycall.Rents]
3
Klibia
15/10/2020 15:11
10
3
Skygrey
RTT
55
bike3.png
5
toulouse
11/02/2020 11:44
10
3
Skygrey
RTT
55
bike3.png
[Bicycall.Rent, Bicycall.Rent]
10
faresbenslama95@gmail.com
10
faresbenslama95@gmail.com
123456
benslama
fares
12345671
["user_id": 10, "lastname": "fares", "email": "faresbenslama95@gmail.com", "phone": "12345671", "password": "123456", "name": "benslama"]
<NSHTTPURLResponse: 0x600003854240> URL: http://localhost:3000/locations Status Code: 200, Headers
Connection = (
"keep-alive"
);
"Content-Length" = (
339
);
"Content-Type" = (
"text/html; charset=utf-8"
);
Date = (
"Mon, 14 Dec 2020 15:50:15 GMT"
);
Etag = (
"W/\"153-s80IUuqdLC0Rkz3oIqCM7x8xP7I\""
);
"Keep-Alive" = (
"timeout=5"
);
"X-Powered-By" = (
Express
);
339 bytes
[Bicycall.Rents, Bicycall.Rents]
3
Klibia
15/10/2020 15:11
10
3
Skygrey
RTT
55
bike3.png
5
toulouse
11/02/2020 11:44
10
3
Skygrey
RTT
55
bike3.png
[Bicycall.Rent, Bicycall.Rent]
<NSHTTPURLResponse: 0x6000038490a0> URL: http://localhost:3000/bikes Status Code: 200, Headers
Connection = (
"keep-alive"
);
"Content-Length" = (
314
);
"Content-Type" = (
"application/json; charset=utf-8"
);
Date = (
"Mon, 14 Dec 2020 15:50:18 GMT"
);
Etag = (
"W/\"13a-G0h70hatF47P4CgaOr94LtJs2ug\""
);
"Keep-Alive" = (
"timeout=5"
);
"X-Powered-By" = (
Express
);
314 bytes
bike.png
http://localhost:3000/bike.png
bike2.png
http://localhost:3000/bike2.png
bike3.png
http://localhost:3000/bike3.png
bike4.png
http://localhost:3000/bike4.png
[Bicycall.Bike, Bicycall.Bike, Bicycall.Bike, Bicycall.Bike]
10
faresbenslama95@gmail.com
10
faresbenslama95@gmail.com
123456
benslama
fares
12345671
["user_id": 10, "email": "faresbenslama95@gmail.com", "lastname": "fares", "name": "benslama", "password": "123456", "phone": "12345671"]
<NSHTTPURLResponse: 0x600003848300> URL: http://localhost:3000/locations Status Code: 200, Headers
Connection = (
"keep-alive"
);
"Content-Length" = (
339
);
"Content-Type" = (
"text/html; charset=utf-8"
);
Date = (
"Mon, 14 Dec 2020 15:50:20 GMT"
);
Etag = (
"W/\"153-s80IUuqdLC0Rkz3oIqCM7x8xP7I\""
);
"Keep-Alive" = (
"timeout=5"
);
"X-Powered-By" = (
Express
);
339 bytes
[Bicycall.Rents, Bicycall.Rents]
3
Klibia
15/10/2020 15:11
10
3
Skygrey
RTT
55
bike3.png
5
toulouse
11/02/2020 11:44
10
3
Skygrey
RTT
55
bike3.png
[Bicycall.Rent, Bicycall.Rent]
【问题讨论】:
收到数据后你必须重新加载tableView。为您的表格视图和 yourTableView.reloadData() 创建一个 @IBOutlet thomashanning.com/uitableview-tutorial-for-beginners 阅读本文会让您了解自己在做什么。 【参考方案1】:当您更新数据源(在您的情况下为 self.rents)时,您还需要重新加载 tableview。
首先你必须从你的tableview中取出一个出口,然后如果你还没有设置它们,你需要设置数据源和委托给自己。
@IBOutlet weak var tableView: UITableView!
didSet
tableView.delegate = self
tableView.dataSource = self
现在您需要在使用 self.rents 进行更改后重新加载 tableview。
DispatchQueue.main.async [weak self] in
self?.tableView.reloadData()
在使用 urlSessionTask 时也要使用 [weak self],否则可能会造成内存泄漏。
session.dataTask(with: request) [weak self] (data,response,error) in
【讨论】:
我应该使用 xcode 中的助手来绑定整个 tableview 并只替换您告诉我要替换的内容吗? 你需要绑定助手,按住control然后拖拽tableview。以上是关于tableview 是空的,但我看到操场上的数据来自 urlsession的主要内容,如果未能解决你的问题,请参考以下文章