Search code examples
iosobjective-cwatchkitwatchos-2

how to extend background expiration time of iPhone app while your app is sync local data with iWatch app?


When iphone app is enter in background mode then ios automatically terminate app after 180 second. If we require to continuously data sync between iphone app to iwatch app. In this situation what can we do?

How to continuously data sync enable between iphone and iwatch when iphone app is in background and time was expired.

Lets see answer for more details.


Solution

  • In this situation we can write below code for continuously execute our app in background.

    AppDelegate.h

    Bool *isBackground = NO;
    - (void)applicationDidEnterBackground:(UIApplication *)application {
    
       NSLog(@"Enter Background");
    
       [self extendBackgroundRunningTime];  //Call function for upadte time
    
       NSLog(@"Time Remaining: %f", [[UIApplication sharedApplication] backgroundTimeRemaining]);
    
       NSLog(@"%d",_isFromBackground);
    }
    

    Function

    - (void)extendBackgroundRunningTime {
        if (_isFromBackground != UIBackgroundTaskInvalid) {
            return;
        }
        NSLog(@"Attempting to extend background running time");
    
        __block Boolean self_terminate = YES;
    
        _isFromBackground = [[UIApplication sharedApplication] beginBackgroundTaskWithName:@"DummyTask" expirationHandler:^{
            NSLog(@"Background task expired by iOS");
            if (self_terminate) {
                [[UIApplication sharedApplication] endBackgroundTask:_isFromBackground];
                _isFromBackground = UIBackgroundTaskInvalid;
            }
        }];
    
        dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
            NSLog(@"Background task started");
    
            while (true) {
                NSLog(@"background time remaining: %8.2f", [UIApplication sharedApplication].backgroundTimeRemaining);
                [NSThread sleepForTimeInterval:10];
            }
    
        });
    }
    

    Hope this may help you.