iphone 4 sdk:检测从后台模式返回

Fra*_*ois 26 background-foreground ios4

如何检测应用程序刚从"后台模式"返回?我的意思是,当用户按下"主页按钮"时,我不希望我的应用程序获取数据(每60秒).但是,我想在应用程序第一次处于前台模式时进行一些"特殊"更新.

我怎样才能检测到这两个事件:

  1. 应用程序进入后台模式
  2. 应用程序进入前台模式

提前致谢.

弗朗索瓦

jha*_*ott 48

以下是如何监听此类事件:

// Register for notification when the app shuts down
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(myFunc) name:UIApplicationWillTerminateNotification object:nil];

// On iOS 4.0+ only, listen for background notification
if(&UIApplicationDidEnterBackgroundNotification != nil)
{
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(myFunc) name:UIApplicationDidEnterBackgroundNotification object:nil];
}

// On iOS 4.0+ only, listen for foreground notification
if(&UIApplicationWillEnterForegroundNotification != nil)
{
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(myFunc) name:UIApplicationWillEnterForegroundNotification object:nil];
}
Run Code Online (Sandbox Code Playgroud)

注意:if(&SomeSymbol)检查确保您的代码可以在iOS 4.0+以及iOS 3.x上运行 - 如果您针对iOS 4.x或5.x SDK构建并将部署目标设置为iOS 3.x,您的应用仍然可以在3.x设备上运行,但相关符号的地址将为零,因此它不会尝试询问3.x设备上不存在的通知(这会使应用程序崩溃).

更新:在这种情况下,if(&Symbol)检查现在是多余的(除非您出于某种原因确实需要支持iOS 3).但是,在使用它之前了解用于检查API是否存在的技术很有用.我更喜欢这种技术,而不是测试操作系统版本,因为您正在检查特定的API是否存在,而不是使用外部知识知道什么操作系统版本中存在哪些API.


Chr*_*s R 5

如果实现UIApplicationDelegate,您还可以作为委托的一部分挂钩函数:

- (void)applicationDidEnterBackground:(UIApplication *)application {
   /*
   Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. 
 If your application supports background execution, called instead of applicationWillTerminate: when the user quits.
   */
    NSLog(@"Application moving to background");
}


- (void)applicationWillEnterForeground:(UIApplication *)application {
  /*
   Called as part of the transition from the background to the active state: here you can undo many of the changes made on entering the background.
   */
    NSLog(@"Application going active");
}
Run Code Online (Sandbox Code Playgroud)

有关协议参考,请参阅http://developer.apple.com/library/ios/#documentation/uikit/reference/UIApplicationDelegate_Protocol/Reference/Reference.html