在将视图控制器添加到 UITabBarController 之前加载数据



在我的应用程序中,一旦用户从LoginViewController登录,他就会被定向到ProfileTabBarController

ProfileTabBarControllerUITabBarController的一个子类。它由三个视图控制器组成,所有这些控制器都需要对配置文件实例的引用。

推送ProfileTabBarController时,它会加载用户的配置文件。成功加载配置文件后,它会在其每个视图控制器上设置对配置文件的引用,然后将它们添加为选项卡项。

我选择这种方法的原因是,如果用户启动应用程序并且他的令牌尚未过期,则应用程序应直接转到ProfileTabController;用户无需再次登录。与其在AppDelegateLoginViewController中复制加载配置文件的代码,我觉得最好将其封装在ProfileTabBarController中。

这种方法的问题在于,在 segue 期间,UITabBarController显示为黑色,因为没有设置视图控制器。我设法通过创建一个LoadingViewController并将其最初设置为唯一的UIViewController来解决此问题ProfileTabController

我的问题是是否有更好的方法来解决这个问题。我真的不喜欢拥有一个没有其他目的的UIViewController然后显示加载图标的想法。

呈现一个没有视图的选项卡视图控制器没有多大意义,所以我认为您给它一个视图控制器来处理这种加载状态的解决方案非常有意义。加入一些很酷的动画来保持用户的娱乐。

也有可能出现问题,配置文件可能无法正确加载。这个过渡视图控制器似乎是放置代码以处理可能错误的好地方。

我能够通过使用NSNotificationCenter来消除加载视图控制器。

  • ProfileTabBarController添加三个视图控制器,然后开始加载配置文件。

override func viewDidLoad(( { super.viewDidLoad((

    self.setupUI()
    self.setupViewControllers()
    self.loadProfile()

}

  • 加载完成后,ProfileTabBarController会发出ProfileDidLoad通知。

let complete = { (profile: profile?

MBProgressHUD.hideHUDForView(self.view, animated: true)
if let profile = profile {
    self.profile = profile
    NSNotificationCenter.defaultCenter().postNotificationName(Notification.ProfileDidLoad, object: self.profile)
} else {
    UIAlertView(
        title: "",
        message: NSLocalizedString("Error loading profile", comment: ""),
        delegate: nil,
        cancelButtonTitle: "OK"
        ).show()
}

}

  • 视图控制器观察ProfileDidLoad通知:

    func setupNotificationObserver(({

        NSNotificationCenter.defaultCenter().addObserver(self, selector: "profileDidLoad:", name: Notification.ProfileDidLoad, object: nil)
    }
    @objc func profileDidLoad(notification: NSNotification){
        if let profile = notification.object as? Profile{
            self.profile = profile
        }
    }
    

这样,视图控制器在登录后立即显示,而无需加载屏幕。

最新更新