iOS NSNotificationCenter来检查应用程序是否从后台到前台

我有一个情况,我必须每次初始化一个对象,当它从背景到前景,并应该使用NSNotificationCenter不与appdelegate,因为我build立一个静态库,所以不会被appdelegate所以请帮助我在相同的。

你有没有尝试过UIApplicationWillEnterForegroundNotification

在调用applicationWillEnterForeground:之前,应用程序还会发布一个UIApplicationWillEnterForegroundNotification通知applicationWillEnterForeground:给感兴趣的对象一个机会来响应转换。

订阅通知:

 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(yourUpdateMethodGoesHere:) name:UIApplicationWillEnterForegroundNotification object:nil]; 

实现一个需要被调用的代码:

 - (void) yourUpdateMethodGoesHere:(NSNotification *) note { // code } 

不要忘记取消订阅:

 [[NSNotificationCenter defaultCenter] removeObserver:self]; 

Swift 3版本

 override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) NotificationCenter.default.addObserver(self, selector:#selector(applicationWillEnterForeground(_:)), name:NSNotification.Name.UIApplicationWillEnterForeground, object: nil) } override func viewWillDisappear(_ animated: Bool) { super.viewWillDisappear(animated) NotificationCenter.default.removeObserver(self) } func applicationWillEnterForeground(_ notification: NSNotification) { .... } 

你也可以使用NSNotification.Name.UIApplicationDidBecomeActive