ios - App从后台进入前台时如何调用方法

标签 ios methods viewdidload foreground

当我的应用程序从后台进入前台时,有没有简单的方法调用方法?我让我的程序在 viewDidLoad 方法中调用方法“nowYouSeeMe”,这在第一次运行应用程序时效果很好。当我使用该应用程序然后按下主页按钮时,它会像往常一样移至后台。现在,当我按下应用程序图标并将它带到前台时,我基本上希望它再次调用 nowYouSeeMe 方法。

-(void)nowYouSeeMe{
  NSLog(@"I'm back");
}

有什么想法吗??

最佳答案

如前所述,在 App Delegate 中有 - (void)applicationDidBecomeActive:(UIApplication *)application;,但大多数时候您需要的信息不是在您的 app delegate 中,而是在您的 View Controller 中。因此你可以使用 NSNotificationCenter。在您的应用委托(delegate)中,您可以执行以下操作:

NSNotificationCenter *center = [NSNotificationCenter defaultCenter];
[center postNotification:[NSNotification notificationWithName:@"appDidEnterForeground" object:nil]];

现在您可以在 UIViewController 的设置代码中设置监听器:

NSNotificationCenter *center = [NSNotificationCenter defaultCenter];
[center addObserver:self selector:@selector(appDidEnterForeground) name:@"appDidEnterForeground" object:nil];

现在,只要应用程序进入前台,方法 appDidEnterForeground 就会在您的 View Controller 上被调用。

但是您甚至不需要自己发布通知,因为它已经在 UIApplication 中定义了。如果向下滚动文档 (UIApplication Class Reference),您会看到在 UIApplication.h 中声明的所有通知,在您的例子中是 UIApplicationWillEnterForegroundNotification。 请注意 UIApplicationWillEnterForegroundUIApplicationDidEnterForeground 之间的区别,但大多数时候您想要使用 UIApplicationWillEnterForeground,只是为了设置一切并在应用程序启动时做好准备显示。

当然,您应该在某处为您的通知名称定义一个常量,如果您不再需要观察者,请将其删除。

编辑:你也可以在你的问题中使用@selector(nowYouSeeMe),错过了

关于ios - App从后台进入前台时如何调用方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23740705/

相关文章:

ios - 如何将我的设备 token (NSData) 转换为 NSString?

ios - 分组 UITableView 中的中心页脚 UIImage - Swift

python - 在实例方法中更新类变量

具有内部 Clear() 方法的 C# 结构

iphone - 在 UIViewController 上加载数据 : viewDidLoad and viewWillAppear - What is the proper logic?

objective-c - UIGestureRecognizer 或 touchesBegan 没有响应

ruby - 在 Ruby 中查找字符串中某个字符的 # 次出现

objective-c - 错误 : Mutating method sent to immutable object for NSMutableArray from JSON file

ios - ViewController 出现两次过渡

ios - 来自 ViewController 外部的 Alamofire 请求