iOS app running in the background

2019-06-10 09:30发布

问题:

I am trying to be able to set how long my app will remain in the background. I want to be able to have the control over how long my app can stay active in the background until it is closed. Is there something I can add to the Info.plist that can set that, with the bool that is the switch to have it run in the background or not?

I have read and found that Apple doesn't let apps remain in the background for longer than 10min, but I have done some testing and found other live apps that are similar to mine, last longer than 10min. I have also found old posts that bypass this by setting and reseting timers before the 10min mark, does this still work with iOS7 and does Apple still accept it?

回答1:

Edit: Misunderstood the questions. Here is a possible alternative.

- (void)applicationDidEnterBackground:(UIApplication *)application{
      UIApplication*    app = [UIApplication sharedApplication];
      task = [app beginBackgroundTaskWithExpirationHandler:^{
        [app endBackgroundTask:task];
        task = UIBackgroundTaskInvalid;
    }];
    // Start the long-running task and return immediately.
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{

        // Do the work associated with the task.
        NSLog(@"Started background task timeremaining = %f", [app backgroundTimeRemaining]);
        // save time to NSUserdefaults
        [[NSUserdefaults standardUserDefaults] setObject:[NSDate date] objectForKey@"startDate"];

        [app endBackgroundTask:task];
        task = UIBackgroundTaskInvalid;
    });

}

- (void)applicationWillTerminate:(UIApplication *)application{
    [[NSUserdefaults standardUserDefaults] setObject:[NSDate date] objectForKey@"terminateDate"];
}

-(void)applicationDidFinishLaunching:(UIApplication)application{
   //get start time & terminate time & then take a diffrence
   NSDate* temporaryDate1 = (NSDate*)[userDefaults objectForKey:@"startDate"];
   NSDate* temporaryDate2 = (NSDate*)[userDefaults objectForKey:@"terminateDate"];
   compare[temporaryDate1,temporaryDate2];
}

Here is a link to check how to compare NSDate instance.