ios - Firebase .childAdded 观察者复制 child

标签 ios firebase swift3 firebase-realtime-database

我试图让我的程序将一个 child 的每个实例添加到一个数组中,但是每当我删除一个 child 然后添加另一个它重复添加的 child 两次,如果我再次这样做,它将重复 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()
    }
}

最佳答案

这可能与您没有调用 reloadData() 有关。在主线程上。

而不仅仅是:

self.contactsTable.reloadData()

尝试:
DispatchQueue.main.async {
    self.contactsTable.reloadData()
}

关于ios - Firebase .childAdded 观察者复制 child ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44803946/

相关文章:

ios - 从 Firebase 数据库异步方法返回值

swift3 - 如何使用 URL(string : ,relativeTo:) 在 swift 3/4 中构造 url

android - 从 android 中的 Firebase 数据库读取特定值

ios - 火力地堡 : Retrieve childByAutoID from Realtime Database

ios - 无法找到 UIApplicationShortcutIcon.init(联系人 : CNContact) for loading contact image in dynamic action

ios - cgcontextaddcurvetopoint 在 swift 3 中不可用

ios - 客户端 (iOS) 上的核心数据缓存来自服务器策略的数据

ios - 导航到苹果 map 上的当前位置

ios - SCNRenderer 不在 iOS 13 上渲染 AVPlayer

ios - 如何从 UI 测试访问 Apple Id "Sign In"对话框?