Home > other >  How to Load More Posts In CollectionView?
How to Load More Posts In CollectionView?

Time:12-05

i am making app with Xcode using Swift , i fetch posts from my WordPress Website, i am very new to Xcode and Swift , i have fetched posts from my Website Successfully , now the problem is that when is try to load more posts (More than 10 posts) , i mean pagination, i see some problems, like when i do pagination after 10th post, it show the next 11-20 posts but it not starts from post 11th but it goes directly to post 20 and because of that , all next posts loaded automatically untill the end of posts, and one more thing when next posts are loading than i can't see the old posts like when 11-20 posts loaded then 1-10 posts are not shown and CollectionView starts from number 11.

this is my code to fetch posts..

 func fetchPostData(completionHandler: @escaping ([Post]) -> Void ) {
   
    self.page  = 1
      let url = URL(string: "https://www.sikhnama.com/wp-json/wp/v2/posts/?categories=6&page=\(page)")!
      
      let task = URLSession.shared.dataTask(with: url) { (data, response, error) in
          
          guard let data = data else {return}
          
          do {
              
              let postsData = try JSONDecoder().decode([Post].self, from: data)
              
              completionHandler(postsData)
              DispatchQueue.main.async {
                  self.collectionView.reloadData()
                  
              }
          }
          
          catch {
              
              let error = error
              print(String(describing: error))
          }
          
          
          
      }.resume()
      
      
      
      
      
      
  }

in ViewDid Load

 self.fetchPostData { (posts) in
    self.newsData = posts }

and this is how i do pagination

func collectionView(_ collectionView: UICollectionView, willDisplay cell: UICollectionViewCell, forItemAt indexPath: IndexPath) {
    if indexPath.row == self.newsData.count - 1 {  //numberofitem count
            updateNextSet()
        }
}

func updateNextSet(){
   self.fetchPostData { (posts) in
  self.newsData = posts
               }

}

CollectionView Code

extension ViewController: UICollectionViewDataSource {

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

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

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
    let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "MovieCollectionViewCell", for: indexPath) as! MovieCollectionViewCell
    
    
    
    
    
    cell.setup(with: newsData[indexPath.row])
    
   
    
   
    
    return cell
    }

please help . thanks

CodePudding user response:

When the next batch of posts come back, you are overwriting the existing posts rather than appending them:

self.fetchPostData { (posts) in
    self.newsData = posts 
}

Instead, you need to append the new posts instead such as by using the = operator.

In addition, you should call reloadData() within the fetchPostData completion handler rather than inside the response of the HTTP request to give your code better separation of concerns.

So the above code would become:

self.fetchPostData { (posts) in
    self.newsData  = posts 
    self.collectionView.reloadData()
}
  • Related