Search code examples
iosiphoneobjective-cios7nsthread

Can't execute function call on X minutes more than once in IOS


I tried to make function that will be invoked every minute (without timer).
When I run the app it executes after one minute and never again.
I probably miss something but can't find what?

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
    NSDate *date = [NSDate date];
    NSDateComponents *dateComponents = [[NSCalendar currentCalendar] components:NSSecondCalendarUnit fromDate:date];

    NSTimeInterval timeSinceLastSecond = date.timeIntervalSince1970 - floor(date.timeIntervalSince1970);
    NSTimeInterval timeToNextMinute = (60 - dateComponents.second) - timeSinceLastSecond;

    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(timeToNextMinute * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{

        [self myFunction];

    });

    return YES;
}

Solution

  •  - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
     {
        [self executeEveryOneMinute];
        return YES:
     }
    
     - (void)executeEveryOneMinute
     {
        [self myFunction]
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(60 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
    
            [self executeEveryOneMinute];
    
        });
     }