2017-05-10 1 views
0

컬렉션보기를 새로 고침하면 데이터가 +1에 의해 중복됩니다. 이 기능을 새로 고치려면 배열에서 중복 된 항목을 피하려면 어떻게합니까? self.posts.removeAll()도 여전히 결과를 사용합니다.Firebase observeSingleEvent가 연속적으로 내 배열에 추가 된 항목을 복제합니다.

var posts = [Post]() { 
    didSet { 
     collectionView?.reloadData() 
    } 
} 

var following = [String]() 
let refreshControl = UIRefreshControl() 

override func viewDidLoad() { 
    super.viewDidLoad() 

    refreshControl.tintColor = UIColor.gray 
    refreshControl.addTarget(self, action: #selector(fetchPosts), for: UIControlEvents.valueChanged) 
    collectionView?.addSubview(refreshControl) 
    collectionView?.alwaysBounceVertical = true 
    fetchPosts() 
} 

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

override func viewWillAppear(_ animated: Bool) { 
    super.viewWillAppear(animated) 
    self.collectionView.reloadData() 
} 

func fetchPosts(){ 
    let ref = FIRDatabase.database().reference() 
    ref.child("users").queryOrderedByKey().observeSingleEvent(of: .value, with: { snapshot in 
     guard let users = snapshot.value as? [String : AnyObject] else { 
      return 
     } 
     print(snapshot.key) 
     for (_,value) in users { 
      if let uid = value["uid"] as? String { 
       if uid == FIRAuth.auth()?.currentUser?.uid { 
        if let followingUsers = value["following"] as? [String : String]{ 
         for (_,user) in followingUsers{ 
          self.following.append(user) 
          print(user) 
         } 
        } 
        self.following.append(FIRAuth.auth()!.currentUser!.uid) 

        ref.child("posts").queryOrderedByKey().observeSingleEvent(of: .value, with: { (snap) in 
         for postSnapshot in snap.children.allObjects as! [FIRDataSnapshot] { 
         let post = postSnapshot.value as! [String : AnyObject] 
         print(snap.key) 

          if let userID = post["userID"] as? String { 
           for each in self.following { 
            if each == userID { 
             print(each) 
             let posst = Post() 

             if let date = post["date"] as? Int, let author = post["author"] as? String, let likes = post["likes"] as? Int, let pathToImage = post["pathToImage"] as? String, let postID = post["postID"] as? String { 

              posst.date = Int(date) 
              posst.author = author 
              posst.likes = likes 
              posst.pathToImage = pathToImage 
              posst.postID = postID 
              posst.userID = userID 

              print(posst) 
              if let people = post["peopleWhoLike"] as? [String : AnyObject] { 
               for (_,person) in people { 
                posst.peopleWhoLike.append(person as! String) 
               } 
              } 


              var postExist:Bool = false 
              for post in self.posts { 
               if post.postID == posst.postID { 
                postExist = true 
                break 
               } 
              } 

              if !postExist { 
               self.posts.append(posst) 
              } 

              self.posts.sort(by: {$0.date! > $1.date!}) 
              self.refreshControl.endRefreshing() 
             } 
            } 
           } 
           self.collectionView.reloadData() 
          } 
         } 
        }) 
       } 
      } 
     } 

    }) 
    ref.removeAllObservers() 
} 

func numberOfSections(in collectionView: UICollectionView) -> Int { 
    return 1 
} 

func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { 
    return posts.count 
} 

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { 
    let cell = collectionView.dequeueReusableCell(withReuseIdentifier: PostCell.identifier, for: indexPath) as! PostCell 

    cell.posts = posts[indexPath.row] 

    let post = posts[indexPath.row] 
    for person in post.peopleWhoLike { 
     if person == FIRAuth.auth()!.currentUser!.uid { 
      cell.like.isHidden = true 
      cell.unlike.isHidden = false 
      break 
     } 
    } 
    return cell 
} 

}

은 솔루션 업데이트되었습니다.

+0

데이터를 배열에 추가 한 후 self.posts.sort (by : {$ 0.date!> $ 1.date!})와 같은 날짜로 정렬 할 수 있습니다. 그러나 콜렉션 뷰를 다시로드하기 위해 스크롤 할 때 중복을 피하려면 도움이 필요합니다. 감사합니다 –

+0

내 대답은 아래의 귀하의 문제를 해결하지 않으면 전체보기 컨트롤러를 업로드해야합니다, 왜냐하면 당신의 코드 중 일부는 이것을 완벽하게 이해하지 못하기 때문입니다. –

+0

전체 코드가 추가되었습니다. 감사합니다 –

답변

0

새로 고침이 활성화되면이 함수가 호출되고 모든 게시물이 다운로드됩니다. 중복 된 문제의 경우 이전 데이터를 제거하지 않고 게시물 배열에 데이터를 계속 추가하는 것처럼 보입니다.

ref.child("posts").queryOrderedByKey().observeSingleEvent(of: .value, with: { (snap) in 

    let postsSnap = snap.value as! [String : AnyObject] 

    self.posts.removeAll() // This will remove previously downloaded posts. 

    // All your other code ... 
관련 문제