Wingzero
Wingzero

Reputation: 9754

iOS how to store time when app goes background

I want to have a feature for my app that user can put app into background, and when user relaunch it, app can check the current time and compared to the old time, say every 1 hour the app can trigger an auto-refresh.

My problem is I don't know how to save the time object when the app goes to background and read it when launching.

Any best practice for this? Thank in advance.

Upvotes: 0

Views: 286

Answers (1)

ZeMoon
ZeMoon

Reputation: 20274

You can use NSUserDefaults to save the time.

Use the app delegate methods:

- (void)applicationWillResignActive:(UIApplication *)application {
    //When application is going into background
    [[NSUserDefaults standardUserDefaults] setObject:[NSDate date] forKey:@"backgroundTime"];
}

- (void)applicationWillEnterForeground:(UIApplication *)application {
    //When application comes back from background state
    NSDate *prevDate = [[NSUserDefaults standardUserDefaults] objectForKey:@"backgroundTime"];
    NSDate *currDate = [NSDate date];

    NSTimeInterval interval = [currDate timeIntervalSinceDate:prevDate];

    if (interval / 3600.0 > 1.0) {
        //Refresh your application
    }
}

Upvotes: 1

Related Questions