0

I am attempting to retrieve a set of data from a firebase realtime db but I've been unable to get it to wait for the data. Here is the code that starts the process:

      if inParm == "Table1" {
         loadQuestions1()
         myTotal = questionArray.count
         loadNextQuestion()
      } else {
         loadQuestions()
      }

Ignore the loadQuestions func that is working since that is pulling from a plist. I'm concerned with the loadQuestions1() func.

Here is the code for that routine

   public func loadMultipleExam(forQuiz quizName: String) throws -> 
      [MultipleChoiceQuestion] {
         curCount = 0
         maxCount = getCount(forQuiz: quizName)
         var questions = [MultipleChoiceQuestion]()
         let dbParm1 = "Questions1/" + mySub
         let myRef1 = myRef.reference(withPath: dbParm1)
         myRef1.observe(.value, with: { snapshot in
            for item in snapshot.children {
               let mItem = QuestionItem(snapshot: item as! DataSnapshot)
               self.questModel.append(Question1(qText: mItem.question, corr: mItem.correctAnswer,
                                               answers:
                                                [
                                                   Answer1(text: mItem.answer1),
                                                   Answer1(text: mItem.answer2),
                                                   Answer1(text: mItem.answer3),
                                                   Answer1(text: mItem.answer4)
                                                ]
               )
               )
               self.questModel.shuffle()
               print(self.questModel)
               //self.configureUI(question: self.questModel.first!, myindex: 1)
            }
         })

         return questions
   }

Now it fires up to the for statement and then it returns to the if statement and continues through loadNextQuestion which loads the data to the screen but at that point there isn't any.  Any help or suggestions would be greatly appreciated.

Douglas W. Palme
  • 251
  • 2
  • 10
  • 1
    `observe` is *asynchronous* -- you can't just return `questions` at the end of the function -- it won't be populated at that point. Look at the linked answer above and investigate "completion handlers" and "callback functions". – jnpdx Dec 10 '21 at 21:08
  • 1
    Swift 5.5 added support for Async/await, which makes async calls look a lot like synchronous calls. You might want to take a look at examples using that. (Although you'll need to use Xcode 13.2 if you want async/await support in iOS ≥ 13. ) – Duncan C Dec 10 '21 at 21:28

0 Answers0