gpt4 book ai didi

ios - 如何修复 UITableView 类,该类在 Firebase 数据库上重复读取两次元素,并且在加载时表为空?

转载 作者:行者123 更新时间:2023-11-29 05:46:25 24 4
gpt4 key购买 nike

我正在尝试从 Firebase 实时数据库读取一系列指令。

我的 Vehicles 节点上有未知数量的信息,因此我仅使用 nextObject 方法来获取函数需要迭代的次数。

问题是在开幕时,我的 table 是空的。当我单击搜索栏时,我的单元格内容确实出现了。我该如何解决这些问题?

这是我的 UITableView 文件:

import UIKit
import FirebaseDatabase
import Alamofire




class Vehicles: UITableViewController,
UISearchResultsUpdating, UISearchBarDelegate {

//variables
var model: NSMutableArray = []
var numberOfVehicles: NSMutableArray = []
var price: NSMutableArray = []
var imagePathString: NSMutableArray = []
var detailpage: NSMutableArray = []



var populator: NSMutableArray = []
var searching = false
var matches = [Int]()
let searchController = UISearchController(searchResultsController: nil)

@IBOutlet weak var InfoTableView: UITableView!

var InfoList: [String] = []

override func viewDidLoad() {
super.viewDidLoad()
loadData()
//this should reload but, it didn't.
self.InfoTableView.reloadData()
//then the searchbar that is good and don't have any problem.
searchingField()
}



func loadData() {
//read data from database
let rootRef = Database.database().reference()
let conditionalRef = rootRef.child("Vehicles")
conditionalRef.observe(.value) {(snap: DataSnapshot) in
// Get all the children from snapshot you got back from Firebase
let snapshotChildren = snap.children
// Loop over all children in Firebase
while let child = snapshotChildren.nextObject() as? DataSnapshot {
// Get code node key and save it to they array
self.populator.add(child.key)
if self.populator.contains("\(child.key)") {
let userRef = rootRef.child("Vehicles").child("\(child.key)")

userRef.observeSingleEvent(of: .value, with: { snapshot in
let userDict = snapshot.value as! [String: Any]

let model1 = userDict["Model"] as! String
self.model.add(model1)

let detail1 = userDict["Detail"] as! String
self.detailpage.add(detail1)

let numberOfVehicles1 = userDict["numberOfVehicles"] as! String
self.numberOfVehicles.add(numberOfVehicles1)

let Price1 = userDict["Price"] as! String
self.price.add(Price1)

let imageURL1 = userDict["imageURL"] as! String
self.imagePathString.add(imageURL1)
}) //end second observeSingleEvent

}
else {
let alert = UIAlertController(title: "Error", message: "No one vehicle found", preferredStyle: UIAlertController.Style.alert)
alert.addAction(UIAlertAction(title: "ok", style: UIAlertAction.Style.default, handler: nil))
self.present(alert, animated: true, completion: nil)
}

} //end searching object in Vehicles node



} //end first observeSingleEvent

}//end func


func searchingField() {
//setup searchbar
tableView.estimatedRowHeight = 50
navigationController?.navigationBar.prefersLargeTitles = true

searchController.searchBar.delegate = self
searchController.searchResultsUpdater = self
searchController.searchBar.backgroundColor = UIColor.white
searchController.obscuresBackgroundDuringPresentation = false
searchController.searchBar.placeholder = "Search"
navigationItem.searchController = searchController
definesPresentationContext = true
let attributes = [
NSAttributedString.Key.foregroundColor : UIColor.black,
NSAttributedString.Key.font : UIFont.boldSystemFont(ofSize: 17)
]
UIBarButtonItem.appearance(whenContainedInInstancesOf: [UISearchBar.self]).setTitleTextAttributes(attributes, for: .normal)
UIBarButtonItem.appearance(whenContainedInInstancesOf: [UISearchBar.self]).title = "Dismiss"
UIBarButtonItem.appearance(whenContainedInInstancesOf: [UISearchBar.self])
}





// MARK: Search Controller
func updateSearchResults(for searchController: UISearchController) {
var regArray = self.model as NSArray as! [String]
if let searchText = searchController.searchBar.text,
!searchText.isEmpty {
matches.removeAll()

for index in 0..<model.count {
if regArray[index].lowercased().contains(
searchText.lowercased()) {
matches.append(index)
}
}
searching = true
} else {
searching = false
}
tableView.reloadData()
}

func searchBarCancelButtonClicked(_ searchBar: UISearchBar) {
searching = false
tableView.reloadData()
}



// MARK: - Table view data source

override func numberOfSections(in tableView: UITableView) -> Int {
return searching ? matches.count : model.count
}

override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {

return searching ? matches.count : model.count
}


override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

let cellIdentifier = "TableCell"

let cell = tableView.dequeueReusableCell(withIdentifier: cellIdentifier) as! Vehicles_cell



let row = indexPath.row
var regArray = self.model as NSArray as! [String]
cell.Label.text = searching ? regArray[matches[row]] : model[row] as! String
cell.Subtitle?.text = "N. Vehicles: \(self.numberOfVehicles[indexPath.row]) - Price: \(self.price[indexPath.row])$"


Alamofire.request("\(self.imagePathString[indexPath.row])").response { response in
guard let image = UIImage(data:response.data!) else {
// Handle error
return
}
let imageData = image.jpegData(compressionQuality: 1.0)
cell.Image.contentMode = .scaleAspectFit
cell.Image.image = UIImage(data : imageData!)
}

return cell
}



override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "ShowrentDetails" {

let myIndexPath = self.tableView.indexPathForSelectedRow!

//save detail1 in UserDefault
let SVDetail = self.detailpage[myIndexPath.row]
let SVDetaildefaults = UserDefaults.standard
SVDetaildefaults.set(SVDetail, forKey: "sv_detail")
SVDetaildefaults.synchronize()
_ = segue.destination
as! Vehicles_Detail
}
}

//IMPOSTA LE DIMENSIONI DELLE CELLE
override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
switch indexPath.row {
default:
return 100
}
}


}

我希望表格在打开时显示数据库中的所有数据,而实际上,除非我单击搜索栏,否则不会重复。并且该表不应重复两次。


编辑(重复的解决方案)

这太尴尬了。这个问题的答案很简单

numberOfSections函数中,我使用address.count代替使用1个Section。所以,我看到的不是重复的单元格,而是 model.count

的新 block 部分

最佳答案

在 Firebase 观察期间获取数据后,您的表格 View 不会重新加载数据,而是在 updateSearchResults() 中重新加载数据。是否在 loadData() 中添加 self.InfoTableView.reloadData() ,位于车辆节点中的 //end Searching 对象 之间//endfirstobserveSingleEvent 右括号解决了这个问题吗?

编辑:重新加载表格 View 数据无法解决 viewDidLoad() 中的问题的原因是它在 loadData() 函数开始迭代之前被调用通过您的 Firebase 数据对象。通过在 Firebase 观察结束时执行此操作,您可以确保在调用重新加载之前已从 Firebase 加载所有数据。

关于ios - 如何修复 UITableView 类,该类在 Firebase 数据库上重复读取两次元素,并且在加载时表为空?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56117746/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com