我正在创建一个简单的应用程序来使用Firebase进行CRUD工作 - 添加,更新和删除。我已经完成了所有这些,除了我有更新问题。
我可以在更新子值时获取对适当用户的引用,并在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通知。
如何正确导航到旧索引并将旧值更改为新值,以便表视图正确更新?
答案 0 :(得分:0)
这是一个临时解决方案,我只能使用一次,之后不起作用:
我创建一个名为“ogFullName”的全局字符串变量,并在子添加代码期间将其设置为全名。然后在我的孩子改变了代码,我将“ogFullName”设置为我想要改变的元素的索引。我用文字解释它有点困难,所以这里是代码:
var ogFullname:String?
func observePeople()
{
let ref = FIRDatabase.database().reference().child("Users")
ref.observeEventType(.ChildAdded, withBlock:
{ (snapshot) in
if let firstname = snapshot.value?.objectForKey("firstname"), lastname = snapshot.value?.objectForKey("lastname")
{
let fullname = "\(firstname) \(lastname)"
self.ogFullname = fullname //the old name
...
这是我的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)"
if let ogname = self.ogFullname
{
if let originalIndex = self.names.indexOf(agnate) //finding the index of the unchanged name
{
self.names[originalIndex] = fullname //setting the old name to the changed one
}
此解决方案每个版本只能运行一次。之后,它继续显示在控制台上显示的更新的相同行为,但不是表视图。