swift - 最后一个数组结果是仅在tableview中显示的结果

时间:2017-11-04 21:30:22

标签: ios arrays swift uitableview

我有一个数组的3个结果,我试图在tableview中显示它们。 数组的结果是正确的,因为我在控制台中打印它们,但是当我尝试在tableview中显示它们时,它取最后的结果并根据来自主数组的元素数量显示3次。 As shown in this image

class DriverEarningsTableView : UITableViewController {

@IBOutlet var myTableView: UITableView!{
    didSet {
        myTableView.dataSource = self
        myTableView.delegate = self
    }
}
override func viewDidAppear(_ animated: Bool) {
    super.viewDidAppear(animated)
    //getRowsCount()
    myTableView.reloadData()
}

override func viewDidLoad() {
    super.viewDidLoad()
    myTableView.dataSource = self
    myTableView.delegate = self
    getRowsCount()
    myTableView.reloadData()
}

override func numberOfSections(in tableView: UITableView) -> Int {

    return 1
}

var titlesArray = [String] ()

func getRowsCount(){
    let userID = Auth.auth().currentUser!.uid
    let ref = Database.database().reference()
    var arrayCount = 0;
    ref.child(Constants.driverTrip).child(userID).observeSingleEvent(of: .value, with: { (snapshot) in

        for child in snapshot.children {
            let snap = child as! DataSnapshot
            let key = snap.key
            //let value = snap.value
            //print("key = \(key)  value = \(value!)")
            self.titlesArray.append(key)
            //print(self.titlesArray)

        }
        arrayCount = self.titlesArray.count
        print(self.titlesArray)
        print (arrayCount)
    })
}

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

   // print (self.titlesArray)
    //print (self.titlesArray.count)
    //return self.titlesArray.count+4
    return self.titlesArray.count

}


override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "cell") as! MyCell

    print("I am IN")
    let userID = Auth.auth().currentUser!.uid
    let ref = Database.database().reference()

    if self.titlesArray.count == 0 {
        cell.passengerName.text = "No Trips Found"
    }
    else{
        var totalEarnings: Double = 0
        for trips in self.titlesArray {
            let trip_id = trips
            ref.child(Constants.TRIP).child(trip_id).observeSingleEvent(of: .value, with: { (snapshot) in
                let value = snapshot.value as? NSDictionary
                let passengerID = value?[Constants.pUid] as? String ?? "Not Found"
                let tripcost = value?[Constants.tripCost] as? Double ?? 0
                print(trip_id)
                print(tripcost)
                cell.tripCost.text = String(tripcost)
                totalEarnings += tripcost
                //self.totalEarnings.text = String(totalEarnings)
                let tripstatus = value?[Constants.tripState] as? String ?? "Not Found"
                var completedTrips = 0
                if tripstatus == "Completed"{
                    completedTrips += 1
                    cell.tripState.text = "Success"
                }
                else if tripstatus == "Canceled" {
                    cell.tripState.text = "Canceled"
                }
                //self.completedTrips.text = String(completedTrips)
                ref.child(Constants.TRIP).child(trip_id).child(Constants.directionDetails).observeSingleEvent(of: .value, with: { (snapshot) in
                    let value4 = snapshot.value as? NSDictionary
                    let mydestlocname = value4?[Constants.destAddress] as? String ?? "Not Found"
                    cell.passengerDestLoc.text = mydestlocname
                    print (mydestlocname)
                })
                ref.child(Constants.RIDERS).child(passengerID).observeSingleEvent(of: .value, with: { (snapshot) in
                    let value2 = snapshot.value as? NSDictionary
                    let riderFName = value2?[Constants.pFirstName] as? String ?? "Not Found"
                    let riderLName = value2?[Constants.pLastName] as? String ?? "Not Found"
                    let imageURL = value2?[Constants.pImageUrl] as? String ?? ""
                    let riderName = riderFName + " " + riderLName
                    cell.passengerName.text = riderName
                    print (riderName)
                    if imageURL == "" {
                        cell.riderProfilePic.image = UIImage(named: "11m.png")
                    }
                    else{
                        let storageRef = Storage.storage().reference(forURL: imageURL)
                        storageRef.getData(maxSize: (1 * 1024 * 1024), completion: {(data, error) -> Void in
                            // Create a UIImage, add it to the array
                            let pic = UIImage(data: data!)
                            cell.riderProfilePic.image = pic
                            cell.riderProfilePic.layer.borderWidth = 1.0
                            cell.riderProfilePic.layer.masksToBounds = false
                            cell.riderProfilePic.layer.borderColor = UIColor.white.cgColor
                            cell.riderProfilePic.layer.cornerRadius = cell.riderProfilePic.frame.size.width/2
                            cell.riderProfilePic.clipsToBounds = true
                            print("textcontent is \(imageURL)")
                        })
                    }

                })
                ref.child(Constants.DRIVERS).child(userID).observeSingleEvent(of: .value, with: { (snapshot) in
                    let value3 = snapshot.value as? NSDictionary
                    let spentTime = value3?[Constants.spentTime] as? Int ?? 0
                    let spentTimeInMins = round(Double(spentTime/60))
                    //self.spentTime.text = "\(spentTimeInMins) Mins"
                })
            })
        }
    }

//cell.passengerName.text = "it works!"
    //myTableView.reloadData()
    return cell
}


}

2 个答案:

答案 0 :(得分:0)

你为什么要做for循环?总是最后得到屏幕上的最后一个值。而是通过array[indexPath.row]访问所需的元素,其中indexPath.row是0..n的单元格编号,因此您的第一个单元格数据应该出现在array[0]中,依此类推。

希望这会有所帮助:)

答案 1 :(得分:0)

除了在tableView(_:cellForRowAt :)方法中不使用for循环外,我相信你也在滥用firebase。除非我误认为observerSingleEvent是一个异步方法。像这样的代码:

dataBase.observeSingleEvent(of: .value, with: { (snapshot) in
  //process value from snapshot
}
tableView.reloadData()

注定要失败,因为在调用observeSingleEvent()方法的完成处理程序之前调用了reloadData。

您希望以这样的方式构建代码:

dataBase.observeSingleEvent(of: .value, with: { (snapshot) in
  //process value from snapshot and install into table view array

  //Tell tableView to reload INSIDE the completion handler!
  tableView.reloadData()
}

声明:

我之前没有使用过FireBase,所以我不确定它的observeSingleEvent()方法是不同步的,但是从我查看的内容看起来确实如此