我正在做一个小游戏。当用户进行游戏并关闭游戏时,应用程序会保存一个时间戳,这样当他返回时,它可以以秒为单位计算他离开的时间。
我的问题是,当应用程序重新打开时它会崩溃。我可以看到这是一个转换问题,但我尝试了各种不起作用的方法。
所以我最后的希望是 Stack Overflow。:-)
我的代码如下:在 AppDelegate.swift 文件中保存日期:
appData.set(Date(), forKey: GameData.lastTimeActiveStamp)
当用户重新打开应用程序时(仍然是 AppDelegate.swift)
GameScene().calculateTimeLeft()
最后是我的 GameScene.swift:
let timeSinceActive = appData.object(forKey: GameData.lastTimeActiveStamp)!
/* Check the difference */
let elapsedTime = Date().timeIntervalSince(timeSinceActive as! Date)
/* Convert this to seconds */
let timeSpentAwayInSeconds = Int(elapsedTime)
/* Find out how many seconds the user had left when he quitted the game */
let currentTimeLeft = appData.integer(forKey: GameData.currentTimeLeft)
/* If the time spent away is larger than the seconds there was left, the game is over */
if timeSpentAwayInSeconds > currentTimeLeft {
/* Game over */
appData.set(0, forKey: GameData.currentTimeLeft)
GameOver()
}
编辑:
忘记粘贴日志:
Could not cast value of type '__NSCFData' (0x1b8c90f30) to 'NSDate' (0x1b8c91b10).
2017-08-29 20:16:49.533396+0200 Sleepy[929:226885] Could not cast value of type '__NSCFData' (0x1b8c90f30) to 'NSDate' (0x1b8c91b10).