我做得正确吗?Swift 3 Xcode加载数据来自Firebase



我当前加载数据的方式在其特定视图控制器上的ViewWillAppear中。我的问题是,我应该将所有数据加载到家庭/主视图控制器上并以这种方式传递数据吗?还是当前的方式我会做得更好?

我知道这是主观的,我正在加载大量数据。

结构:

如果您不希望数据在应用程序过程之间持续存在(当应用程序关闭时,则数据已清除),则可以使用全局变量。在检索数据时,我建议您在AppDelegate中创建一个名为retrieveFromFirebase()的函数,其中包含应用程序中所有UIViewControllers在应用程序中检索数据所需的所有代码。那你应该在里面称呼它

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

然后,在您的功能中,您应该将快照的值分配给早期声明的全局变量。

示例:

这是如何为此设置AppDelegate.swift的一个示例:

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
  }

,当您到达所需的ViewController时,将viewDidAppear功能设置为:

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

您可以在当前模块中的任何地方使用用户名。

希望它有帮助!

最新更新