Firebase .childAdded观察者复制儿童

时间:2017-06-28 13:29:55

标签: ios firebase swift3 firebase-realtime-database

我试图让我的程序将一个子项的每个实例添加到一个数组但是每当我删除一个孩子然后添加另一个重复添加了两次子项,如果我再次执行它会重复3次,依此类推我删除和添加了多少次。添加和删​​除主要在下面的函数中处理,我无法弄清楚它为什么会重复它们。

func fetchContacts(completion: @escaping () -> ()){
    contacts = [Contact]()
    let userRef = ref.child("users").child(user).child("contacts")

    userRef.observe(.childAdded, with: { (snapshot) in
        if let dictionary = snapshot.value as? [String: AnyObject]{
            print(snapshot)
            let contact = Contact()
            contact.setValuesForKeys(dictionary)
            self.contacts.append(contact)
        }
        self.contactsTable.reloadData()
        completion()
    }, withCancel: nil)

    userRef.observe(.childRemoved, with: { (snapshot) in
        if let dictionary = snapshot.value as? [String: AnyObject]{
            let contact = Contact()
            contact.setValuesForKeys(dictionary)
            if let i = self.contacts.index(where: { $0.name == contact.name }) {
                self.contacts.remove(at: i)
            }
        }
        self.contactsTable.reloadData()
        completion()
    }, withCancel: nil)
}

以下是处理删除以及如何在viewDidLoad中调用函数的地方:

override func viewDidLoad() {
    contactsTable.delegate = self
    contactsTable.dataSource = self
    contactsTable.rowHeight = 65
    super.viewDidLoad()
    fetchContacts(){
        self.contactsTable.reloadData()
    }
}

func handleDelete(phone: String, completion: @escaping () -> ()){
    let userRef = ref.child("users").child(user).child("contacts")
    userRef.child(phone).removeValue { (error, ref) in
        if error != nil {
            print("Error: \(error)")
        }
        completion()
    }
}

1 个答案:

答案 0 :(得分:2)

这可能与你没有在主线程上调用A fatal error has been detected by the Java Runtime Environment: Internal Error (os_windows_x86.cpp:149), pid=3580, tid=4088 # guarantee(result == EXCEPTION_CONTINUE_EXECUTION) failed: Unexpected result from topLevelExceptionFilter 有关。

而不仅仅是:

reloadData()

尝试:

self.contactsTable.reloadData()