ios - 获取数据但无法正确显示
问题描述
我正在获取一些数据并显示在我的屏幕上。
func getAllCatogory(){
ViewUtils.addActivityView(view: self.view)
TransportManager.sharedInstance.AllCatogory { (dt, err) in
ViewUtils.removeActivityView(view: self.view)
if let _ = err{
}else{
do {
let decoder = JSONDecoder()
decoder.keyDecodingStrategy = .convertFromSnakeCase
guard let str = dt as? String else { return }
let res = try decoder.decode([AllCatagories].self, from:str.data(using: .utf8)!)
self.allCategory = res
self.collectionView.reloadData()
print(res.count) // getting count 2
print(self.allCategory.count as Any) getting count 2
}
catch {
print(error)
}
}
}
}
但是在我的收藏视图中,当我要附加或打印它时,它不会出现。
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "HomeCollectionCell", for: indexPath) as! HomeCollectionCell
let ct = self.allCategory[indexPath.item]
print(ct.menuName as Any) // getting null
//cell.productName.text = ct.menuName
return cell
}
不知道可能是什么问题。对此有任何帮助吗?
提前致谢 !
更新 :
class AllCatagories: Codable{
let image : String?
let isActive : Int?
let items : [Item]?
let menuCode : String?
let menuName : String?
enum CodingKeys: String, CodingKey {
case image
case isActive = "is_active"
case items
case menuCode = "menu_code"
case menuName = "menu_name"
}
}
struct Item : Codable {
let menuCode : String?
let name : String?
enum CodingKeys: String, CodingKey {
case menuCode = "menu_code"
case name
}
}
这是我正在使用的模型类。主线程重新加载集合视图意味着确切的位置?
更新 :
[
{
"menu_code" : "NDS",
"items" : [
{
"unit" : "Nos",
"name" : "Chapathi\/Pulkas",
"quantity" : 2
},
{
"unit" : "Cup",
"name" : "Palya\/Curry",
"quantity" : 1
}
],
"is_active" : 1,
"image" : "nds.jpg",
"menu_name" : "Normal Diet South"
},
{
"menu_code" : "NCCD",
"items" : [
{
"menu_code" : "NDS",
"name" : "Monday"
},
{
"menu_code" : "NDN",
"name" : "Tuesday"
}
],
"is_active" : 1,
"image" : "NCCD.jpg",
"menu_name" : "Normal Combo Corporate Diet"
}
]
我的 json 响应在这里
解决方案
如果您指定convertFromSnakeCase
必须删除编码键,这就是convertFromSnakeCase
并且尽可能的声明成员/属性是非可选的,而不是相反。在这种特殊情况下,您会收到解码错误。
struct AllCatagories: Codable {
let image : String
let isActive : Int
let items : [Item]
let menuCode : String
let menuName : String
}
struct Item : Codable {
let unit : String?
let name : String
let quantity : Int?
let menuCode : String?
}
并在主线程上重新加载集合视图
DispatchQueue.main.async {
self.collectionView.reloadData()
}
推荐阅读
- qt - Qt - 如何将 QByteArray 发送到 QserialPort
- amazon-web-services - Does GCP have an Iac tool just like CloudFormation of AWS?
- arduino - 射频识别
不适用于新的 ARDUINO UNO WiFi REV2 - android - Create a RecyclerView with multiple view from layouts
- pyspark - Dask 等效于 pyspark 超前和滞后功能
- python - PyTesseract 处理单个图像的速度非常慢
- spring-boot - Spring Boot 通过 PUT 上传文件
- python - MongoDB Atlas 身份验证在 Python 上失败
- python - 如何在文件的每一行中找到最大的数字
- python - Python中基于多元线性回归的聚类数据