xHow to save UISwitch state whenever the application is quit (Swift)

大憨熊 提交于 2019-12-06 11:26:43

In AppDelegate class, in applicationDidEnterBackground post a notification, so your view controller will be able to be notified when app goes in background:

func applicationDidEnterBackground(application: UIApplication!) {
    NSNotificationCenter.defaultCenter().postNotificationName("kSaveSwitchesStatesNotification", object: nil);   
}

In your viewcontroller class add this code:

override func viewDidLoad() {
    super.viewDidLoad()
    self.restoreSwitchesStates();

    NSNotificationCenter.defaultCenter().addObserver(self, selector: "saveSwitchesStates", name: "kSaveSwitchesStatesNotification", object: nil);
}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}

func saveSwitchesStates() {
    NSUserDefaults.standardUserDefaults().setBool(spanish!.on, forKey: "spanish");
    NSUserDefaults.standardUserDefaults().setBool(algebra!.on, forKey: "algebra");
    NSUserDefaults.standardUserDefaults().setBool(amerCult!.on, forKey: "amerCult");
    NSUserDefaults.standardUserDefaults().setBool(bio!.on, forKey: "bio");
    NSUserDefaults.standardUserDefaults().setBool(col!.on, forKey: "col");

    NSUserDefaults.standardUserDefaults().synchronize();
}

func restoreSwitchesStates() {
    spanish!.on = NSUserDefaults.standardUserDefaults().boolForKey("spanish");
    algebra!.on = NSUserDefaults.standardUserDefaults().boolForKey("algebra");
    amerCult!.on = NSUserDefaults.standardUserDefaults().boolForKey("amerCult");
    bio!.on = NSUserDefaults.standardUserDefaults().boolForKey("bio");
    col!.on = NSUserDefaults.standardUserDefaults().boolForKey("col");
}

First thing add viewcontroller as an observer for the notification posted when app goes in background. When this notification will be triggered it will call saveSwitchesStates() method which will save switches states in NSUserDefaults. Also in viewDidLoad() call restoreSwitchesStates() which will read stored bools for switches states from NSUserDefaults

Use NSUserDefaults to save there state when application is going to close and load them back when the app launches. Tutorial explaining how to save data using NSUserDefaults

http://www.icodeblog.com/2008/10/03/iphone-programming-tutorial-savingretrieving-data-using-nsuserdefaults/

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!