简体   繁体   中英

Launch saved state at startup of app (swift)

what the app does so far is that users go through an array of strings by clicking a button, when they leave and remove the app from multitasking it saves where they were in the array. But when you startup the app you get stuck at the first String but you have to press the button called showFunFact() to get where you left off. I would like the current one to come at startup Here's the code:

let TechnologyfactBook = TechFactBook()
var TechfactIndex = 0

override func viewDidLoad() {
    super.viewDidLoad()  
}

@IBAction func showFunFact() {
    if (UIApplication.sharedApplication().applicationIconBadgeNumber != 0){
        UIApplication.sharedApplication().applicationIconBadgeNumber = 0
    }
    if (TechfactIndex >= TechnologyfactBook.TechfactsArray.count) {
        self.TechfactIndex = 0
    }

    TechfactIndex = NSUserDefaults.standardUserDefaults().integerForKey("ByteLocation")

    TechByteLabel.text = TechnologyfactBook.TechfactsArray[TechfactIndex]
    TechfactIndex++
    NSUserDefaults.standardUserDefaults().setInteger(TechfactIndex, forKey: "ByteLocation")
    NSUserDefaults.standardUserDefaults().synchronize()
}

Just add the code that loads the last location into the viewDidLoad. What the code does is first it checks if the user's last location is greater than the starting position, which I assume is 0. Once it checks this, it will assign the text value to the value that the user last had.

override func viewDidLoad() {
    super.viewDidLoad()

    //Checks if the value that is saved into the app is greater than the
    //starting position the app first starts at (assuming index 0?)
    if NSUserDefaults.standardUserDefaults().integerForKey("ByteLocation") != 0 {
        TechByteLabel.text = TechnologyfactBook.TechfactsArray[TechfactIndex]   
    } else {
        //The code that first displays the values if the user
        //just started the app 
    }   
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM