2016-09-25 66 views
0

我對編碼領域相當陌生,我知道這個問題可能在其他地方也有類似的回答,但是當涉及到Firebase時,它可能不會。我正在關注這個答案(Adding sections, separated by dates, to UITableView in Swift),但在實現.ChildAdded和insertRowAtIndexPath時遇到了複雜問題。我的代碼如下:Firebase + Swift TableView按日期排序

var ref: FIRDatabaseReference! 
var mileageDatabase: [FIRDataSnapshot]! = [] 
var retrieveDates: [(String)] = [] 
var uniqueDates: [(String)] = [] 

struct tripDataset { 
    let date: String 
    let purpose: String 
} 
var tripItems = Dictionary<String, Array<tripDataset>>() 

override func viewDidLoad() { 
    super.viewDidLoad() 
    self.tableView = UITableView(frame: self.tableView.frame, style: .Grouped) 

    let nib = UINib(nibName: "TripTableViewCell", bundle: nil) 
    self.tableView.registerNib(nib, forCellReuseIdentifier: "cell") 
    configureDatabase() 

} 

func configureDatabase() { 
    self.ref = FIRDatabase.database().reference() 
    if let user = FIRAuth.auth()?.currentUser { 
     self.ref.child("mileage").queryOrderedByChild("user").queryEqualToValue(user.uid).observeEventType(.ChildAdded, withBlock: { (snapshot) in 
      self.mileageDatabase.insert(snapshot, atIndex: 0) 

      let snapValues = snapshot.value as! Dictionary< String, AnyObject> 
      let snapDates = snapValues["date"] as! String 
      let snapPurpose = snapValues["purpose"] as! String 

      self.retrieveDates.append(snapValues["date"] as! String) 
      self.uniqueDates = Array(Set(self.retrieveDates)) 

      if self.tripItems.indexForKey(snapDates) == nil { 
       self.tripItems[snapDates] = [tripDataset(date: snapDates, purpose: snapPurpose)] 
      } else { 
       self.tripItems[snapDates]!.append(tripDataset(date: snapDates, purpose: snapPurpose)) 
      } 

      self.tableView.insertRowsAtIndexPaths([NSIndexPath(forRow: 0, inSection: 0)], withRowAnimation: .Automatic) //Stuck hereeee..... 

     }) 
    }   
} 

override func numberOfSectionsInTableView(tableView: UITableView) -> Int { 
    return self.uniqueDates.count 
} 

override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { 
    return self.tripItems[section].count 
} 

override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { 
    let cell = tableView.dequeueReusableCellWithIdentifier("cell", forIndexPath: indexPath) as! TripTableViewCell 

    cell.dateTimeLabel.text = self.uniqueDates(indexPath.section) 
    cell.purposeLabel.text = self.tripItem[self.uniqueDates(indexPath.section)]["purpose"] 

    return cell 
} 

override func tableView(tableView: UITableView, titleForHeaderInSection section: Int) -> String? { 
return self.uniqueDates(section) 
} 

我知道這裏有很多錯誤,有沒有人可以相應地指導我? Firebase的所有異步本質都會讓我的流程複雜化。

+0

什麼問題,什麼是你想要做..? – Dravidian

+0

@Dravidian按日期排序tableview,其中每一天是一個部分本身。這個想法是將一天內的所有旅程分組在一個部分中。 – Koh

回答

0

試試這個。 更改下面的代碼從

self.retrieveDates.append(snapValues["date"] as! String) 

self.retrieveDates.insert(snapValues, at : 0)