Swiftaccnt Swiftaccnt - 7 months ago 18
iOS Question

What function gets called when loading app from homescreen?

I want to be able to change the background color of my app depending on the time of day. I believe the way to go about this is saying if the hour component is greater than whatever number, set the background to the nighttime background, otherwise it's the daytime background.

To test out what I was worried about, I threw

timeLabel.text = NSDateFormatter.localizedStringFromDate(NSDate(), dateStyle: .NoStyle, timeStyle: .FullStyle)

. This shows the time that the app loads. This also obviously keeps updating if I kill the app and reload it completely.

However, if the user goes the the home screen or goes to a different app, then comes back to this the time isn't going to be updated. It will show the time the app was first loaded up. Only if the user completely kills the app, which obviously can't be relied on, will the correct time be shown.

So in my example if my "switch to nighttime time" was 5pm, if the user loads up at the at at 4:30 and then goes to the homescreen, loads up the app at 5pm, nothing will be changed as the stored time will still be 4:30.

I tried throwing the code in
and nothing changed.

What code is run when the app is loaded up from being on the homescreen or coming back from another app?


You want to key off of the UIApplicationDidBecomeActiveNotification event. Try this:

override func viewDidLoad() 

        selector: "applicationDidBecomeActive:",
        name: UIApplicationDidBecomeActiveNotification,
        object: nil)

func applicationDidBecomeActive(notification: NSNotification) 
    // do something when the app is active again.
    timeLabel.text = NSDateFormatter.localizedStringFromDate(NSDate(), dateStyle: .NoStyle, timeStyle: .FullStyle)