我正在製作一個簡單的應用程序,使用Firebase執行CRUD工作 - 添加,更新和刪除。我已經完成了所有這些,除了我有一個更新問題的事實。在更新後在Firebase中查找項目的舊值
我可以在更新子值時獲得對正確用戶的引用,並使其在Firebase控制檯中成功更新。這是我用的代碼:
let ref = FIRDatabase.database().reference().child("Users")
ref.observeEventType(.ChildAdded, withBlock: { (snapshot) in
guard let dictionary = snapshot.value as? [String:AnyObject] else { return }
if self.firstNameField.text == dictionary["firstname"] as? String
{
if let lastname = dictionary["lastname"]
{
print("Here is the lastname of the current person \(lastname)")
guard let firstname = self.firstNameField.text, lastname = self.lastNameField.text, dateOfBirth = self.dateOfBirthField.text, zipcode = Int(self.zipcodeField.text!) else
{
print("Form not valid")
return
}
let properties: [String: AnyObject] = ["firstname": firstname, "lastname": lastname, "Date of Birth": dateOfBirth, "Zipcode": zipcode]
let currentKey = snapshot.key
ref.child(currentKey).updateChildValues(properties, withCompletionBlock: { (error, ref) in
if error != nil
{
print("We have an error updating the data \(error)")
}
print("We were able to update the entry in the reference \(ref)")
})
}
}
}, withCancelBlock: nil)
我的問題是TableViewController不是隻要我解僱EditViewController更新正確的索引。 tableview.reloadData()方法對此不起作用,所以我想我需要在我的ChildChanged方法中修復它。下面是該代碼:
ref.observeEventType(.ChildChanged, withBlock: { (snapshot) in
print("One of the entries were changed so we're reloading the table view")
if let firstname = snapshot.value?.objectForKey("firstname"), lastname = snapshot.value?.objectForKey("lastname")
{
let fullname = "\(firstname) \(lastname)"
self.names[I_Need_This_Index] = fullname
print(fullname)
dispatch_async(dispatch_get_main_queue())
{
self.tableView.reloadData()
}
}
}, withCancelBlock: nil)
上面的代碼是在一個稱爲observePeople()方法,它是viewDidLoad方法期間調用。 observePeople()方法處理了ChildAdded,ChildRemoved和ChildChanged通知。
如何正確導航到舊索引並將舊值更改爲新值,以便表視圖正確更新?
只需在更新值時更改'dataSource [indexOfCellThatChanged]'.->調用reloadTableView。 – Dravidian
我會改變它什麼?我如何從我的其他視圖控制器訪問它? –