在iOS中,有一种方法可以在我退出应用程序后的一段时间后执行一段代码吗?

时间:2014-01-17 03:01:27

标签: ios

退出应用程序后,在一定时间后有没有办法执行一段代码?

我的意思是按主页按钮

3 个答案:

答案 0 :(得分:1)

https://developer.apple.com/library/ios/documentation/uikit/reference/UIApplicationDelegate_Protocol/Reference/Reference.html#//apple_ref/occ/intfm/UIApplicationDelegate/applicationDidEnterBackground

在iOS 4.0及更高版本的applicationDidEnterBackground上调用appDelegate方法,在按下主页按钮并且用户的视图退出到主屏幕时。然后,您可以使用[NSTimer]

https://developer.apple.com/library/mac/documentation/cocoa/reference/foundation/classes/NSTimer_Class/Reference/NSTimer.html

稍后执行您想要的任何代码。但请注意,iOS喜欢applicationDidEnterBackground在大约5秒内返回;您的应用程序可以使用方法beginBackgroundTaskWithExpirationHandler启动后台任务。

答案 1 :(得分:1)

来自Apple docs

  

您的app delegate的 applicationDidEnterBackground:方法有   大约5秒钟完成任务并返回。在实践中,   这种方法应该尽快返回。如果方法有   在时间用完之前没有返回,你的应用程序被杀死并被清除   记忆。如果您还需要更多时间来执行任务,请致电    beginBackgroundTaskWithExpirationHandler:方法请求后台执行时间,然后启动任何长时间运行的任务   次要线程。无论你是否开始任何背景   任务, applicationDidEnterBackground:方法仍然必须退出   在5秒内。

阅读整篇文章以获取更多信息,但基本上当有人按下主页按钮时,将调用applicationDidEnterBackground:方法。在该方法中,使用beginBackgroundTaskWithExpirationHandler:在单独的线程上设置代码。

希望有所帮助!

答案 2 :(得分:1)

如果您想在一段时间后执行某些代码,则可以使用NSTimer.Thanks

[NSTimer scheduledTimerWithTimeInterval:60.0
                                                 target:self
                                               selector:@selector(MethodName)
                                               userInfo:nil
                                                repeats:YES];
相关问题