iphone 4 sdk:检测后台模式的返回 [英] iphone 4 sdk : detect return from background mode

查看:169
本文介绍了iphone 4 sdk:检测后台模式的返回的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

How can I detect that an app has just returned from "background mode"? I mean, I don't want my app to fetch data (each 60 sec) when the user press the "home button". But, I'd like to make some "special" update the first time the app is in foreground mode.

如何检测这两个事件:


  1. app进入后台模式

  2. app进入前台模式

提前致谢。

François

推荐答案

以下是监听此类事件的方法:

Here's how to listen for such events:

// 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];
}

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

Note: The if(&SomeSymbol) checks ensure that your code will work on iOS 4.0+ and also on iOS 3.x - if you build against an iOS 4.x or 5.x SDK and set the deployment target to iOS 3.x your app can still run on 3.x devices but the address of relevant symbols will be nil, and therefore it won't try to ask for notifications that don't exist on 3.x devices (which would crash the app).

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

Update: In this case, the if(&Symbol) checks are now redundant (unless you really need to support iOS 3 for some reason). However, it's useful to know this technique for checking if an API exists before using it. I prefer this technique than testing the OS version because you are checking if the specific API is present rather than using outside knowledge of what APIs are present in what OS versions.

这篇关于iphone 4 sdk:检测后台模式的返回的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆