I am making a chat calculator application using Swift. My goal is to reset my application after 10 minutes (in other words, set all my shortcuts to $ 0.00 and set the defaults to NSUserDefaults).
I put these 3 functions in my ViewController.swift file:
func compareTimes(opens: NSDate?, closes: NSDate?) {
if(opens!.timeIntervalSinceReferenceDate-closes!.timeIntervalSinceReferenceDate>600) {
reset()
}
}
func openApp() {
openingTime = NSDate()
let defaults = NSUserDefaults.standardUserDefaults()
closingTime = defaults.objectForKey(closeKey) as! NSDate?
if (closingTime != nil) {
compareTimes(openingTime, closes: closingTime)
}
}
func closeApp() {
closingTime = NSDate()
let defaults = NSUserDefaults.standardUserDefaults()
defaults.setObject(closingTime, forKey: closeKey)
}
In my AppDelegate, I call two of these methods:
func applicationDidEnterBackground(application: UIApplication) {
ViewController().closeApp()
}
func applicationWillEnterForeground(application: UIApplication) {
ViewController().openApp()
}
Note that when the application is closed, time is recorded, and when the application is open, time is also recorded. These times are compared and if 10 minutes are reset()called.
My problem is when reset()all my variables that represent UILabels and UITextFields are called become null and I get an error
: .
reset() :
func reset() {
billField.text=""
tipLabel.text = "+ "+formatter.stringFromNumber(0)!
totalLabel.text = formatter.stringFromNumber(0)
total2.text = formatter.stringFromNumber(0)
total3.text = formatter.stringFromNumber(0)
total4.text = formatter.stringFromNumber(0)
let defaults = NSUserDefaults.standardUserDefaults()
defaults.setObject("15", forKey: key1)
defaults.setObject("18", forKey: key2)
defaults.setObject("20", forKey: key3)
defaults.synchronize()
percentages.append(0.1)
percentages.append(0.1)
percentages.append(0.1)
percentButton.setTitle("15%", forSegmentAtIndex: 0)
percentButton.setTitle("18%", forSegmentAtIndex: 1)
percentButton.setTitle("20%", forSegmentAtIndex: 2)
}