2021年4月28日星期三

Issue when fetching random documents from firestore in swift iOS

I want to fetch random documents from firestore every time the user opens my application.

I implemented the functionality correctly and It fetches documents randomly as required.

my problem is that when for instance the random document is the last document in my firestore database it would stop loading new documents as there is no more documents after it. because I have implemented also the load next documents when the user reaches the bottom of the page.

how can I solve this issue?

please any help on how to fix this issue? I want to load random documents without it stopping the load of documents when it reaches the final document before it should.

here is my code:

   func loadData(){                    let randomShops = db.collection("Shops");          key = randomShops.document().documentID                      db.collection("Shops").whereField("__name__", isGreaterThanOrEqualTo: self.key!).order(by: "__name__", descending: true).limit(to: 8).getDocuments(){              querySnapshot, error in              if let error = error {                  print(error.localizedDescription)              }else {                  self.lastDoc = querySnapshot?.documents[(querySnapshot?.documents.endIndex)! - 1]                  self.shops = querySnapshot!.documents.compactMap({addShop(dictionary: $0.data())})                  DispatchQueue.main.async {                      self.tableView.reloadData()                  }              }                      }   }  

then I would fetch new documents as the user scrolls down. but if the document that appears is the last document in my firestore database it wouldn't load more documents even though not all the documents have been loaded.

func getNextShops() {

        db.collection("Shops").order(by: "__name__").start(afterDocument: lastDoc!).limit(to: 8).getDocuments(){ docs, err in              self.docsCount = docs?.count              if  self.docsCount == 0{                  self.tableView.stopLoading()                  return              }else{              if let err = err {                  print(err.localizedDescription)              }else{                      docs?.documents.forEach{ data in                                                       self.shops.append(addShop(dictionary: data.data())!)                              DispatchQueue.main.async {                                  self.tableView.reloadData()                                                                }                      }                  self.lastDoc = docs?.documents[(docs?.documents.endIndex)! - 1]                  self.lastDocID = self.lastDoc?.documentID                            }              }          }           }  
https://stackoverflow.com/questions/67309758/issue-when-fetching-random-documents-from-firestore-in-swift-ios April 29, 2021 at 09:07AM

没有评论:

发表评论