How do I make my App run an NSTimer in the background?

前端 未结 2 809
眼角桃花
眼角桃花 2020-11-30 01:41

I\'m making a benchmark App for test purposes ONLY. I am not intending this to go to the App Store.

What I need is my NSTimer to continue running on the background

相关标签:
2条回答
  • 2020-11-30 01:55

    XCode 6.3.1, for iOS 8.3

    There are big diffrences that I've encountered between the apps. behavior while plugged in to your Mac running XCode using debugger and the same apps. behavior while unplugged.

    At current iOS version, 8.3, at most your app is allotted is 180 seconds to run in the background for finite long running task with an expiration handler.

    No matter what you try, with your phone unplugged your app will be killed by the system in 180 seconds or earlier. I've done a significant amounts of tests and tricks to confirm this. See my post...

    My NSTimer Post

    Here is a neat way to tell how much time is left for your app to run before termination, keep in mind that you are not guaranteed this time.

    NSTimeInterval backgroundTimeRemaining = [[UIApplication sharedApplication] backgroundTimeRemaining];
    
    if (backgroundTimeRemaining == DBL_MAX)
    {
        NSLog(@"background time remaining = undetermined");
    }
    else
    {
        NSLog(@"background time remaining = %0.2f sec.", backgroundTimeRemaining);
    }
    

    Hope this helps your investigation. Cheers!

    0 讨论(0)
  • 2020-11-30 01:57

    I figured it out by myself, for anyone else with a similar problem, what I did was to first turn on the location update flag on your Info.plist file. To do this, you must add the Key called "Required Background Modes" on Xcode 4, then as a value, select "App registers for location updates"

    I have a timer declared like so in my .h file:

    NSTimer *silenceTimer;
    @property (nonatomic, retain) NSTimer *silenceTimer;
    

    Then on the .m file, I declared it like so:

    UIBackgroundTaskIdentifier bgTask;
    UIApplication  *app = [UIApplication sharedApplication];
    bgTask = [app beginBackgroundTaskWithExpirationHandler:^{
        [app endBackgroundTask:bgTask]; 
    }];
    self.silenceTimer = [NSTimer scheduledTimerWithTimeInterval:300 target:self
    selector:@selector(startLocationServices) userInfo:nil repeats:YES];
    

    Finally, on the selector method, I made the following:

    -(void)startLocationServices {
        [locationManager startUpdatingLocation];
        [locationManager stopUpdatingLocation];
    }
    

    This will create a timer that starts and immediately stops location services after 5 minutes. This will be enough for the app to stay alive indefinately, unless you kill the process.

    0 讨论(0)
提交回复
热议问题