【发布时间】:2016-04-07 18:27:20
【问题描述】:
我有一个运行计时器的应用,即使应用退出或手机关机,计时器也应该继续运行。
所以我尝试使用shouldSaveApplicationState 和shouldRestoreApplicationState 来做到这一点。我将这两种方法和willFinishLaunchingWithOptions 添加到我的 appDelegate 中,并为涉及的每个视图控制器、导航控制器和标签栏控制器设置恢复 ID。
然后在我想恢复的视图控制器上我这样做了:
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 断开连接的情况下尝试相同的操作时,就好像我根本没有设置状态恢复,应用程序完全忽略它,只显示第一个视图控制器。而且我什至无法调试,因为当我将手机连接到 Xcode 时,它可以正常工作。同样的事情也发生在模拟器上。如果我使用 Xcode 的按钮恢复工作。如果我只是从模拟器本身打开和关闭应用程序,它不会。
有什么想法吗?
【问题讨论】:
标签: ios xcode swift state-restoration