1

The way I currently load my data is in the viewWillAppear on their specific view controllers. My question is should I load all the data on the Home/Main View Controller and pass the data that way? Or is the current way Im doing it better?

I know this is subjective, I'm loading ALOT of data.

Denis
  • 570
  • 9
  • 23

1 Answers1

1

Structure:

If you do not want the data to persist between app processes (when the app is closed the data is cleared), you can use Global Variables. When it comes to retrieving data, I suggest you to create a function in AppDelegate called retrieveFromFirebase(), containing every piece of code needed to retrieve data in your app, for all the UIViewControllers of your app. Then you should call it inside

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {}

Then, inside your function, you should assign the snapshot's value to the global variable declared earlier.

Example:

This is an example of how to setup AppDelegate.swift for this:

import UIKit
import CoreData
import Firebase

//declaration of the global variable
var username = String()

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {

    var window: UIWindow?

    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
        FIRApp.configure()
        retrieveFromFirebase()
        return true
    }

    func retrieveFromFirebase(){
        // get the data from Firebase
        let ref = FIRDatabase.database().reference()
        ref.child("username").observe(FIRDataEventType.value, with: { snapshot in
            username = snapshot.value! as! String
        })

    }

  // other methods from AppDelegate.swift

  }

And when you get to the desired ViewController, set your viewDidAppear function to this:

override func viewDidAppear(_ animated: Bool){
     super.viewDidAppear(animated)
     yourLabel.text = username
}

And you can just use your username anywhere in the current Module.

Hope it helps!

Community
  • 1
  • 1
Mr. Xcoder
  • 4,719
  • 5
  • 26
  • 44
  • Be aware that you should not force-unwrap the snapshot's value if you're not sure that it's not nil. If it may be nil, use guard-statements instead of `snapshot.value!` – Mr. Xcoder Mar 05 '17 at 12:23