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

查看:15
本文介绍了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. 应用进入后台模式
  2. 应用进入前台模式

提前致谢.

弗朗索瓦

推荐答案

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

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 设备上运行,但相关符号的地址将为 nil,因此它不会尝试请求在 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天全站免登陆