- Create a Scheduler
NSBackgroundActivityScheduler API similar to an NSTimer object.
NSBackgroundActivityScheduler *activity = [[NSBackgroundActivityScheduler alloc]
initWithIdentifier:@"com.example.MyApp.updatecheck"];
- Configure Scheduler Properties
activity.tolerance = 10 * 60;activity.interval = 30 * 60;activity.repeats = YES;
QualityOfService : The default value is NSQualityOfServiceBackground leave it.
- Schedule Activity with scheduleWithBlock
[activity
scheduleWithBlock:^(NSBackgroundActivityCompletionHandler completion) {
// Perform the activity
self.completion(NSBackgroundActivityResultFinished);
}];
- Detect Whether to Defer Activity
While a lengthy activity is running, the activity may now requiring deferral.
For example, power source is disconnected.
Activity should call shouldDefer value of YES indicates that the block should finish up and invoke its completion handler .
if ([activity.shouldDefer]) {
// Wrap up processing and prepare to defer activity
self.completion(NSBackgroundActivityResultDeferred);
} else {
// Continue processing
self.completion(NSBackgroundActivityResultFinished);
};
- Stop Activity
[activity invalidate];
- Specify Nondeferrable Background Activities
NSOperationQueue *myQueue = [[NSOperationQueue alloc] init];
id myBackgroundActivity = [[NSProcessInfo processInfo]
beginActivityWithOptions: NSActivityBackground
reason: @"Doing important background work"];
[myQueue addOperationWithBlock:^{
// Do important background work here
[[NSProcessInfo processInfo] endActivity:myBackgroundActivity];
}];