当我的应用程序在 ios 后台终止时如何执行代码 [英] how to execute code when my app terminated in background in ios

查看:19
本文介绍了当我的应用程序在 ios 后台终止时如何执行代码的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 iOS 中,我们都知道有一个 AppDelegate 方法 applicationWillTerminate,当我的应用程序正在运行时(即不在后台)被用户关闭时调用它.但是当我的应用在后台运行时被终止(被用户关闭或被操作系统杀死)时,我想做一些事情(例如保存数据).

In iOS, we all know that there is AppDelegate method applicationWillTerminate, and it is called when my app is closed by user when it is currently running(i.e. not in background). But I want to do something(save data, for example) when my app is terminated(closed by user or killed by OS) when it runs in background.

PS:我的应用可以在后台运行.

PS: my app can run in background.

你有什么解决办法吗?谢谢.

Do you have any solutions? thanks.

推荐答案

对不起,你应该使用 applicationWillTerminate:

Sorry but you should use applicationWillTerminate:

这个方法让你的应用知道它即将被终止并且完全从记忆中清除.您应该使用此方法执行任何您的应用程序的最终清理任务,例如释放共享资源,保存用户数据,并使计时器失效.您对此的实施方法大约有五秒钟的时间来执行任何任务并返回.如果该方法在时间到期之前没有返回,系统可能会杀死整个过程.

This method lets your app know that it is about to be terminated and purged from memory entirely. You should use this method to perform any final clean-up tasks for your app, such as freeing shared resources, saving user data, and invalidating timers. Your implementation of this method has approximately five seconds to perform any tasks and return. If the method does not return before time expires, the system may kill the process altogether.

适用于不支持后台执行或链接的应用针对 iOS 3.x 或更早版本,该方法总是在用户调用时调用退出应用程序.对于支持后台执行的应用, 此方法一般不会在用户退出应用时调用,因为应用在这种情况下,只需移动到后台.但是,这种方法可能在应用程序在后台运行的情况下调用(未暂停)并且系统出于某种原因需要终止它.

For apps that do not support background execution or are linked against iOS 3.x or earlier, this method is always called when the user quits the app. For apps that support background execution, this method is generally not called when the user quits the app because the app simply moves to the background in that case. However, this method may be called in situations where the app is running in the background (not suspended) and the system needs to terminate it for some reason.

因此,如果您还需要在用户手动终止应用时保存数据,请使用 applicationDidEnterBackground,如果您的应用支持后台模式,则会调用它.

So if you need to save data ALSO when user manually kill the app use applicationDidEnterBackground that it's called if your app support background mode.

这篇关于当我的应用程序在 ios 后台终止时如何执行代码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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