如何根据Swift中使用的最后一个viewController打开应用程序?

时间:2016-03-28 21:50:35

标签: ios swift nsuserdefaults

我目前有一个测验游戏应用程序,其中每一轮由不同的视图控制器表示。当用户关闭应用程序并稍后重新打开应用程序时,我希望它保持相同的分数并保持在最后一次的同一个viewcontroller上。我相信NSUserDefaults是要走的路,但不知道如何设置它以记住它最后一轮。任何帮助将不胜感激!

1 个答案:

答案 0 :(得分:2)

您可以使用以下方法创建用户默认对象:

// Create an object reference to the NSUserDefaults class
let defaults = NSUserDefaults.standardUserDefaults()

您可以请求并设置此NSUserDefaults类的对象,该对象在关闭和打开应用程序时将保持不变。

// Set a string for a key
defaults.setObject("a string", forKey: "myVar")

// Request the object associated with the key:
let myVar : String = defaults.stringForKey("myVar")

只要您想保存对象,就可以保存和更新对象的值。如果您在启动应用程序时保存要显示的View Controller的StoryBoard ID,那么只要应用程序出现,您就可以重新打开它:

// Create a reference to the Storyboard file
let storyboard : UIStoryboard = UIStoryboard(name: "Main", bundle: nil)

// Create a reference to the ViewController you want to open
let vc : UIViewController = storyboard.instantiateViewControllerWithIdentifier("ID FROM NSUserDefaults")

// Present the ViewController
dispatch_async(dispatch_get_main_queue(), {
    self.presentViewController(vc, animated: true, completion: nil)
})