Swift Firebase UIRefreshControl 创建重复的帖子

Posted

技术标签:

【中文标题】Swift Firebase UIRefreshControl 创建重复的帖子【英文标题】:Swift Firebase UIRefreshControl creates duplicate posts 【发布时间】:2018-02-09 16:03:08 【问题描述】:

当我在这个视图控制器上为我的 tableview 数组使用 UIRefreshControl 时,它只会添加两个重复的帖子,使其成为 3 个相同的帖子,而不是只显示已经存在的 1 个。我在不同的视图控制器上有一个 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")
        
    )

【问题讨论】:

【参考方案1】:

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

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

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

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

然后重新加载您的表格视图。

【讨论】:

谢谢Badhan Ganesh,我总是对很明显的东西有问题 lmao

以上是关于Swift Firebase UIRefreshControl 创建重复的帖子的主要内容,如果未能解决你的问题,请参考以下文章

Firebase 与 Swift

无法将 Firebase 导入 Swift 类

新的 Firebase 数据导致 TableView 单元格闪烁 (Firebase/iOS/Swift)

查询和 Firebase 中的位置(swift 3)

设置值 Firebase - Swift 3

使用 Firebase (Swift) 进行单元测试