0

I want to load the required data in the AppDelagate so this is what I currently have in place:

        // Override point for customization after application launch.
        FirebaseApp.configure()
        FirebaseFunctions().getCompanies()
        DispatchGroup().wait()
        return true
    }

The function FirebaseFunctions().getCompanies() looks like the following:

func getCompanies(){
        DispatchGroup().enter()
        let db = Firestore.firestore()
        db.collection("companies").getDocuments() { (querySnapshot, err) in
            if let err = err {
                print("Error getting documents: \(err)")
            } else {
                for document in querySnapshot!.documents {
                    let company = Company(name: document.documentID, discount: document.data()["discount"] as! String, website: document.data()["website"] as! String, code: document.data()["code"] as! String, categories: document.data()["categories"] as! String)
                    LocalData.companies.companyList.append(company)
                }
            }
            DispatchGroup().leave()
        }
    }

However, when I use these functions and attempt to access my LocalData Class where the data is being stored, I am met with an error because they are loaded asynchronously. How can I delay the app in the AppDelagate until the data is loaded so that my UI can have access to the data?

Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807
helloworld12345
  • 176
  • 1
  • 4
  • 22
  • 1
    Don't wait. Learn to understand asynchronous data processing. – vadian Aug 23 '20 at 04:27
  • 1
    The answer to “how do I wait” is invariably “don’t”. If you block the main thread at the wrong time (especially at start up), not only do you have a substandard UX (the app looks like it’s frozen), but your app may be summarily terminated by the watchdog process for being unresponsive. These methods were made asynchronous for a reason, so don’t fight it. If your app can’t have any meaningful UI while this initial request is in progress, then present some UI that makes this clear (e.g. a `UIActivityIndicatorView`), start the request, and when it’s done, remove the spinner and present your UI. – Rob Aug 23 '20 at 04:33
  • 1
    The question here is 1) Why are you loading data in your app delegate? You should follow the MVC pattern (Model-View-Controller) pattern and use the C)ontroller to control your data - that would include loading it. Can you clarify what you're asking and why you're not using that design pattern? How are you using that data? – Jay Aug 23 '20 at 14:06
  • Thank you all for all of the help! I am new to working with Swift, so all of your help is much appreciated. I decided to load the data just prior to the segue to the ViewController for which it is required, and everything is working perfectly now! – helloworld12345 Aug 23 '20 at 14:20

0 Answers0