Katie
Katie

Reputation: 267

Delaying IBAction Button

I want to delay this button for 23 hours, which is 82800 seconds. It should work fine, the button does delay after one click, however when I switch to another view controller, or re-enter the application, the button delay function fails to work as it just pops back to clickable button after switching to another view controller or re-starting the application.

here is the code:

- (IBAction)save:(id)sender
{

    UIButton *theButton = (UIButton *) sender;
    theButton.enabled = NO;
    [self performSelector:@selector(enableButton:) withObject:theButton afterDelay:82800.0];
}

- (void)enableButton:(UIButton *)button
{
    button.enabled = YES;
}

I am looking for the code that allows this button to be delayed for 23 hours, no matter if I quit the application or switch to another view controller.

please help

Upvotes: 0

Views: 211

Answers (1)

Andrey Chernukha
Andrey Chernukha

Reputation: 21808

You should use NSUserDefaults. When save: method is called check current date [NSDate date] and save it into the user defaults. Then (when time has already passed) you retrieve the saved date from the defaults and compare it to the current date. If 23 hours have already passed you enable the button

UPDATED:

this how you save the date:

- (IBAction)save:(id)sender
{

UIButton *theButton = (UIButton *) sender;
theButton.enabled = NO;
[[NSUserDefaults standardUserDefaults] setObject:[NSDate date] forKey:@"savedDate"];
[[NSUserDefaults standardUserDefaults] synchronize];
}

then (in future) you fetch the saved date:

NSDate* savedDate = [[NSUserDefaults standardUserDefaults] objectForKey:@"savedDate"];

if ([[NSDate date] timeIntervalSinceDate:savedDate] >= 82800.0 )
{
    theButton.enabled = YES;// you need to keep the reference to the button
}

Upvotes: 1

Related Questions