ios - Swift Firebase UIRefreshControl 创建重复的帖子

标签 ios arrays swift uitableview firebase

当我在这个 View Controller 上为我的 tableview 数组使用 UIRefreshControl 时,它只是添加了两个重复的帖子,使它成为 3 个相同的帖子,而不是只显示已经存在的 1 个。我在不同的 View Controller 上有一个 UIRefreshController,它们工作正常,但我认为这与我的 firebase 调用有关,因为我正在检查 loggedInUser 以及他们关注的人并将这些帖子添加到数组中。不确定如何将我的调用切换到它只是刷新而不是复制的位置。谢谢。

override func viewDidLoad() {
    super.viewDidLoad()

    databaseRef = Database.database().reference()

    locationManager.delegate = self
    locationManager.distanceFilter = kCLLocationAccuracyNearestTenMeters
    locationManager.desiredAccuracy = kCLLocationAccuracyBest
    locationManager.startUpdatingLocation()
    locationManager.stopUpdatingLocation()


    // refresh control
    let refreshControl = UIRefreshControl()
    refreshControl.addTarget(self, action: #selector(refreshControlAction(refreshControl:)), for: UIControlEvents.valueChanged)
    self.feedTableView.insertSubview(refreshControl, at: 0)

}

override func viewWillAppear(_ animated: Bool) {
    super.viewWillAppear(animated)

    if CLLocationManager.locationServicesEnabled() {
        switch(CLLocationManager.authorizationStatus()) {
        case .notDetermined, .restricted, .denied:
            print("No access")
            fetchPosts(refreshing: false, refreshControl: nil)
        //getAllPostsWithoutLocation(refreshing: false, refreshControl: nil)
        case .authorizedAlways, .authorizedWhenInUse:
            print("Access")
            fetchPostsWithLocation(refreshing: false, refreshControl: nil)
            //getAllPosts(refreshing: false, refreshControl: nil)
        }
    } else {
        print("Location services are not enabled")
    }

}


@objc func refreshControlAction(refreshControl: UIRefreshControl) {

    if CLLocationManager.locationServicesEnabled() {
        switch(CLLocationManager.authorizationStatus()) {
        case .notDetermined, .restricted, .denied:
            print("No access")
            fetchPosts(refreshing: true, refreshControl: refreshControl)
        //getAllPostsWithoutLocation(refreshing: true, refreshControl: refreshControl)
        case .authorizedAlways, .authorizedWhenInUse:
            print("Access")
            fetchPostsWithLocation(refreshing: true, refreshControl: refreshControl)
            //getAllPosts(refreshing: true, refreshControl: refreshControl)
        }
    } else {
        print("Location services are not enabled")
    }

}

func fetchPostsWithLocation(refreshing: Bool, refreshControl: UIRefreshControl?) {
    Database.database().reference().child("user_profiles").child((loggedInUser?.uid)!).child("following").observe(.value, with: { snapshot in
        if snapshot.exists() {
            MBProgressHUD.showAdded(to: self.view, animated: true)
            let databaseRef = Database.database().reference()
            // retrieves all users from database
            databaseRef.child("user_profiles").queryOrderedByKey().observeSingleEvent(of: .value, with: { (usersSnapshot) in
                let users = usersSnapshot.value as! [String: AnyObject]
                // retrieve user's following list and append it
                for (_, value) in users {
                    print(value)
                    if let userID = value["uid"] as? String {
                        if userID == Auth.auth().currentUser?.uid {
                            print(value)
                            if let followingUsers = value["following"] as? [String : String] {
                                for (_,user) in followingUsers {
                                    self.following.append(user)
                                }
                            }
                            // append user's id to see own posts
                            //self.following.append(Auth.auth().currentUser!.uid)
                            // retrieve all posts from the database
                            databaseRef.child("posts").queryOrderedByKey().observeSingleEvent(of: .value, with: { (postsSnapshot) in
                                let posts = postsSnapshot.value as! [String: AnyObject]
                                // retrieve posts of each follower and user
                                for (_, post) in posts {
                                    for (_, postInfo) in post as! [String: AnyObject] {
                                        if let followingID = postInfo["uid"] as? String {
                                            for each in self.following {
                                                if each == followingID {
                                                    guard let uid = postInfo["uid"] as! String! else {return}
                                                    guard let caption = postInfo["caption"] as! String! else {return}
                                                    guard let downloadURL = postInfo["download_url"] as! String! else {return}
                                                    guard let name = postInfo["businessName"] as! String! else {return}
                                                    guard let timestamp = postInfo["timestamp"] as! Double! else {return}
                                                    let date = Date(timeIntervalSince1970: timestamp/1000)
                                                    guard let address = postInfo["businessStreet"] as! String! else {return}
                                                    guard let state = postInfo["businessCity"] as! String! else {return}
                                                    guard let postID = postInfo["postID"] as! String! else {return}

                                                    let lat = Double(postInfo["businessLatitude"] as! String)
                                                    let long = Double(postInfo["businessLongitude"] as! String)
                                                    let businessLocation = CLLocation(latitude: lat!, longitude: long!)

                                                    let latitude = self.locationManager.location?.coordinate.latitude
                                                    let longitude = self.locationManager.location?.coordinate.longitude
                                                    let userLocation = CLLocation(latitude: latitude!, longitude: longitude!)

                                                    let distanceInMeters: Double = userLocation.distance(from: businessLocation)
                                                    let distanceInMiles: Double = distanceInMeters * 0.00062137
                                                    let distanceLabelText = String(format: "%.2f miles away", distanceInMiles)

                                                    let post = Post(uid: uid, caption: caption, downloadURL: downloadURL, name: name, date: date, address: address, state: state, distance: distanceLabelText, postID: postID)

                                                    self.feeds.append(post)
                                                    self.tableView.reloadData()

                                                    self.refreshControl?.endRefreshing()
                                                }
                                                self.feeds.sort {$0.date.compare($1.date) == .orderedDescending}
                                                //self.feeds.sort {$0.distance.compare($1.distance) == .orderedAscending}

                                               self.tableView.reloadData()
                                            }
                                        }
                                    }
                                }
                                MBProgressHUD.hide(for: self.view, animated: true)
                            }) { (error) in
                                print(error.localizedDescription)
                            }
                        }
                    }
                }

            })
        } else {
            print("Not following anyone")
        }
    })
}

最佳答案

当来自 firebase 的 api 调用返回时,您只是将结果附加到数组中而不删除旧内容。

在将结果添加到数组的 fetchPostsWithLocation 方法中执行此操作:

self.following.removeAll()
self.following.append(user)

self.feeds.removeAll()
self.feeds.append(post)

然后重新加载您的 TableView 。

关于ios - Swift Firebase UIRefreshControl 创建重复的帖子,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48709709/

相关文章:

ios - 重新排序集合查看单元格 buggy

ios - 来自iOS应用中youtube播放列表的URL

python - 查找(并记录)numpy 数组切片的最大值

python - 在用 `NumPy` 的 `numba` 装饰的函数内创建 `@jit(nopython=True)` 数组?

php - 在php中取消设置编码数组后没有索引的json

swift - 如何在tableHeaderView中放置动态多行UILabel

Swift Float 到 UInt8 的转换没有必要吗?

ios - Swift UICollectionView 工作很奇怪,只注册第二次点击

ios - 如何将 Alamofire 与 AEXML 或 SWXMLHASH 结合使用

android - C++通用多平台获取mac地址的解决方案