表视图显示iOS Swift中使用Firestore?的重复数据

yk9xbfzb  于 2023-05-19  发布在  iOS
关注(0)|答案(3)|浏览(99)

这里我使用FireStore数据库。我正在将用户表数据提取到表视图单元格中。在表视图中,列出所有具有“跟随”按钮选项的用户。如果用户第一次运行时间表视图未复制数据,则当用户关闭应用程序并再次返回时,转到人员建议选项卡以列出所有用户,并且其所有用户都是重复的。
下面是屏幕截图:

import UIKit

 class peopleViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {

@IBOutlet weak var tableView: UITableView!

var users: [Users] = []

override func viewDidLoad() {
    super.viewDidLoad()

    title = "People"
    loadUsers()

}


func loadUsers() {

    API.User.observeUser { (user) in
        self.isFollowing(userId: user.id!, completed: { (value) in
            user.isFollowing = value

            self.users.append(user)
            self.tableView.reloadData()

        })
    }

}

func isFollowing(userId: String, completed: @escaping (Bool) -> Void) {
    API.Follow.isFollowing(userId: userId, completed: completed)
}

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    if segue.identifier == "ProfileSegue" {
        let profileVC = segue.destination as! UserViewController
        let userId = sender  as! String
        profileVC.userId = userId
        profileVC.delegate = self as? UserViewControllerDelegate
    }
}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {

    return users.count
}

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "PeopleTableViewCell", for: indexPath) as! peopleTableViewCell

    let user = users[indexPath.row]
    print("letuser::::\(user)")
    cell.user = user
    cell.delegate = self
    return cell
}



 }
  extension peopleViewController: PeopleTableViewCellDelegate {
  func goToProfileUserVC(userId: String) {
    performSegue(withIdentifier: "ProfileSegue", sender: userId)

 }
}

下面是如何从firestore获取数据的代码:

func observeUser(completion: @escaping (Users) -> Void) {

    db.collection("users")
        .getDocuments() { (querySnapshot, err) in
            if let err = err {
                print("Error getting documents: \(err)")
            } else {

                self.userList.removeAll()

                var user : Users?
                for document in querySnapshot!.documents {

                     user = Users.transformUser(postDictionary: document.data(), key: document.documentID)
    //                        self.userList.append(user!)
                    completion(user!)
                }

    //                    completion(user!)

            }
    }
}
hi3rlvi2

hi3rlvi21#

在func loadUsers()上,在self.users.append(user)行之前写入self.users.removeAll()
如果这不是问题所在,那么你必须从数组中删除所有重复项。
要做到这一点,你必须创建一个函数,删除重复的,例如。

func removeMyDuplicates{
    var newListOfUsers:[User] = []

    for user in self.users{
        var added = false
        for newUser in self.newListOfUsers{
            if(user.id == newUser.id){
                added = true
            }
        }
        if !added{
            newUsers.append(user)
        }
    }
    self.users = newUsers
}

并且在重新加载表视图之前调用func

ig9co6j1

ig9co6j12#

因为你在数组中添加了相同的数据。可以尝试在loadUsers方法中清空数组吗?

func loadUsers() {

        self.users = []

        API.User.observeUser { (user) in
            self.isFollowing(userId: user.id!, completed: { (value) in
                user.isFollowing = value

                self.users.append(user)
                self.tableView.reloadData()

            })
        }
    }
olhwl3o2

olhwl3o23#

我正面临着同样的问题。在我的例子中,有时addSnapshotListener会被调用10次。这是因为监听器在系统上存储缓存。就像我们面对通知中心观察员的问题一样。
要解决这个问题,我们必须获取所有以前添加的侦听器并将其删除。

//Store old listeners in array
var listenerRegistrations: [ListenerRegistration] = []
let listener = db.collection("yourCollection").addSnapshotListener { (snapshot, error) in
    // Handle snapshot updates or errors here
}
listenerRegistrations.append(listener) 

// Remove all listener registrations
for registration in listenerRegistrations {
    registration.remove()
}
// Clear the array after removing all registrations
listenerRegistrations.removeAll()

相关问题