当您的应用与iWatch应用同步本地数据时,如何延长iPhone应用的后台到期时间?

时间:2016-04-27 09:59:46

标签: ios objective-c watchkit watch-os-2

当iphone应用程序进入后台模式时,ios会在180秒后自动终止应用程序。如果我们要求iphone应用程序与iwatch应用程序之间连续数据同步。在这种情况下我们能做什么?

当iphone应用程序处于后台并且时间已过期时,如何在iphone和iwatch之间连续进行数据同步启用。

让我们看一下答案,了解更多详情。

1 个答案:

答案 0 :(得分:-2)

在这种情况下,我们可以在下面编写代码,以便在后台持续执行我们的应用程序。

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);
}

功能

- (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];
        }

    });
}

希望这可以帮助你。