2017-10-14 71 views
1

我有一個方法從FireBase獲取數據,將其保存在本地並將其加載到UITableView中。它運作良好。從服務器swift更新數組中的更改

現在,這個觀察者(rootGenerals.observe())正在運行,並且每次在服務器上更改數據時都會進行更新。

我的問題是,我不想重新加載整個表,一旦我得到一個新的數據(就像我現在所做的那樣),我只想更新表中具體更改的行或替換行的位置( IndexPath)如果分數已經改變。

任何想法如何做到這一點?只需要一些指導,瞭解在這種情況下處理的最佳方式。

rootGenerals.observe(.value, with: { snapshot in 
     if !snapshot.exists() { return } 

     let general = snapshot.value as! NSDictionary 

     if let users : NSDictionary = general.object(forKey: "users") as? NSDictionary 
     { 
      if (self.usersFromDB?.count != 0) { 
       // Update table rows 
       self.arrRecords = [] 
      } 
      else { 
       // Create table from scratch 
       self.usersFromDB = users 

       for user : Any in users.allKeys { 
        let userDict : NSDictionary = users.object(forKey: user as! String) as! NSDictionary 
        let record : Record = Record() 

        record.displayName = userDict.object(forKey: "name") as! String 
        record.time   = userDict.object(forKey: "time") as! Int 
        record.solvedLogos = userDict.object(forKey: "logos_solved") as! Int 
        record.deviceId  = userDict.object(forKey: "device_id") as! String 
        record.raw   = userDict 

        self.arrRecords.append(record) 
       } 

       self.sortRecords() 
      } 
     } 
    }) 
+0

我想你可以使用'.childChanged'事件類型來檢測指定引用的孩子何時更新或更改 – 3stud1ant3

回答

0

,如果你想要更新的特定索引路徑使用

tableView.reloadRows(at: your_indexpath_array, with: your_Animation) 

爲表中的使用插入新行

tableView.beginUpdates() 
tableView.insertRows(at: your_indexpath_array, with: your_Animation) 
tableView.endUpdates() 
+0

謝謝,但這不是我問的問題。請閱讀問題,我知道如何更新一個UITableView單元格 –

0

嘗試使用這樣的:

rootGenerals.observe(.childAdded, with: { snapshot in 
    //your code 
}) 

所以每次添加新的兒童用戶時,它只會讀取n新數據

+0

但是,如果孩子更新並未添加?什麼是最好的方式來同步服務器中更新的和在tableview中屬於它的同一行? –

+0

當您剛剛運行您的應用程序時,它首先讀取您的Firebase中的每個孩子。如果在代碼已經運行時添加新的子代,它將只讀取新的子代。然後,您可以重新加載整個表格或只在表格中插入新行。對於孩子的更新,對於更換的孩子也有類似的方法。希望我回答了所有問題,在這裏您可以找到官方文檔中的所有方法https://firebase.google.com/docs/database/ios/lists-of-data –