ios - 状态恢复仅在连接到 Xcode 时有效

标签 ios xcode swift state-restoration

我有一个运行计时器的应用程序,即使应用程序退出或手机关闭,计时器也应该继续运行。 所以我尝试使用 shouldSaveApplicationStateshouldRestoreApplicationState 来做到这一点。我将方法和 willFinishLaunchingWithOptions 添加到我的 appDelegate 中,并为涉及的每个 View Controller 、导航 Controller 和标签栏 Controller 设置恢复 ID。 然后在我想恢复的 View Controller 上我这样做了:

override func encodeRestorableStateWithCoder(coder: NSCoder) {
    coder.encodeObject(startDate, forKey: "startDate")
    coder.encodeObject(startTime, forKey: "startTime")
    coder.encodeObject(elapsedTime, forKey: "elapsedTime")
    coder.encodeObject(playing, forKey: "playing")
    coder.encodeObject(timerLabel.text, forKey: "timerLabelText")
    super.encodeRestorableStateWithCoder(coder)
}

override func decodeRestorableStateWithCoder(coder: NSCoder) {
    startDate = coder.decodeObjectForKey("startDate") as! NSDate
    startTime = coder.decodeObjectForKey("startTime") as! NSTimeInterval
    elapsedTime = coder.decodeObjectForKey("elapsedTime") as! NSTimeInterval
    playing = coder.decodeObjectForKey("playing") as! Bool
    timerLabel.text = (coder.decodeObjectForKey("timerLabelText") as! String)
    super.decodeRestorableStateWithCoder(coder)
}

override func applicationFinishedRestoringState() {
    if playing {
        elapsedTime += startDate.timeIntervalSinceNow
        play()
    }
}

现在这是奇怪的部分。当我的手机连接到 Xcode 并且我使用 Xcode 的播放和停止按钮启动和退出应用程序时,一切正常。但是,当我在手机与 Xcode 断开连接的情况下尝试同样的事情时,就好像我根本没有设置状态恢复一样,应用程序完全忽略它,只显示第一个 View Controller 。而且我什至无法调试,因为当我将手机连接到 Xcode 时,它​​就可以正常工作了。同样的事情发生在模拟器上。如果我使用 Xcode 的按钮,恢复工作。如果我只是从模拟器本身打开和关闭应用程序,它不会。

有什么想法吗?

最佳答案

当用户主动从多任务菜单中“终止”您的应用时,状态恢复不起作用。它仅在系统在后台静默终止您的应用程序以回收资源(例如内存)时有效。

基本原理(以下是我自己的推测/解释)是,状态恢复的全部目的是让用户回到他们上次离开的应用程序,因为如果它从未终止(从用户的角度来看)。

但如果用户明确终止该应用,则意味着他们不希望它“仍在运行,就像他们离开时一样”。

来源: This part of Apple's docs指出:

  • The system automatically deletes an app’s preserved state when the user force quits the app. Deleting the preserved state information when the app is killed is a safety precaution. (As a safety precaution, the system also deletes preserved state if the app crashes twice during launch.) If you want to test your app’s ability to restore its state, you should not use the multitasking bar to kill the app during debugging. Instead, use Xcode to kill the app or kill the app programmatically by installing a temporary command or gesture to call exit on demand.

从 Xcode(“停止按钮”)中终止应用会复制“非用户启动的终止”,因此它尊重状态保存/恢复流程。

关于ios - 状态恢复仅在连接到 Xcode 时有效,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34586124/

相关文章:

ios - 如何将 Storyboard链接到 View Controller

ios - 如何使用我的 ios 应用程序提供的图像打开 Instagram 应用程序?

swift - 从文件夹引用填充 Interface Builder 中的 NSImage

javascript - HttpRequest 使用来自数组 Parse.com Cloudcode 的多个 URL

ios - swift api SecKeyCreateEncryptedData 使用的额外认证数据是什么?

ios - GCM 推送通知返回错误消息 "GCM registration is not ready with auth credentials...."

ios - 在 UIImageView 中创建滑动功能

c++ - 将 Objective C 格式的代码转换为纯 C++

ios - 不兼容的整数到指针的转换

ios - 桥接 swift 和 objective-c