我在 appDelegate 中看到了几个方法,我不确定仅在其中一些方法中存储和重新存储用户状态是否涵盖所有场景?
func applicationWillResignActive(application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
stopTasks()
setSharedPrefrences()
}
func applicationDidEnterBackground(application: UIApplication) {
// 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, this method is called instead of applicationWillTerminate: when the user quits.
stopTasks()
setSharedPrefrences()
}
func applicationWillEnterForeground(application: UIApplication) {
// 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.
startTasks()
getSharedPrefrences()
}
func applicationDidBecomeActive(application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
startTasks()
getSharedPrefrences()
connectGcmService(application)
}
func applicationWillTerminate(application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
stopTasks()
setSharedPrefrences()
disconnectGcmService(application)
}
我应该只存储\恢复其中的一部分吗? 我应该何时断开并重新连接到 GCM 服务?
我的恢复是多余的吗?
保持一个本地标志说恢复已经完成是不切实际的,因为应用程序可能会破坏它?
最佳答案
了解 The App Lifecycle: Execution States for Apps在 Apple 的 iOS 应用程序编程指南中。
此外,UIApplicationDelegate
中有关您在问题中提到的方法的文档在调用时包含非常详细的信息。取the documentation for applicationWillResignActive
举个例子。
didEnterBackground
前面总是有willResignActive
,因此无需运行相同的代码。willEnterForeground
总是跟在didBecomeActive
之后,但是didBecomeActive
也可以在其他情况下调用(见下文)。willResignActive
可以被调用而无需didEnterBackground
被调用,例如10% 电量警告或来电。如果用户拒绝调用,您的应用将保留在前台,然后调用didBecomeActive
来告诉您该应用再次处于事件状态。willTerminate
在现代 iOS 应用程序中永远不会被调用。在 iOS 支持多任务处理之前,它在 iOS 2 和 3 中使用。由于现在的应用程序会在用户“退出”时移至后台,因此不再使用此事件。 (当操作系统在后台由于内存压力而杀死您的应用程序时,它会立即被杀死而不会执行任何更多代码。)
总结:
stopTasks
/startTasks
应该在willResignActive
和didBecomeActive
中。- 可以在
willResignActive
/didBecomeActive
或didEnterBackground
/willEnterForeground
中保存/恢复用户数据。我可能会选择后者。
关于ios - 我什么时候应该在 ios swift 上存储和重新存储到钥匙串(keychain)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35360453/