Skip to content

Instantly share code, notes, and snippets.

@WilliamDenniss
Last active December 16, 2015 16:40
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save WilliamDenniss/f697aa7f0037c1be7ba0 to your computer and use it in GitHub Desktop.
Save WilliamDenniss/f697aa7f0037c1be7ba0 to your computer and use it in GitHub Desktop.
Encapsulates `beginBackgroundTaskWithExpirationHandler` in a safer manner (should never crash the app with "active assertions beyond permitted time"). For a longer discussion see: http://bit.ly/ZVDo0V
// nb. backgroundTask is a member variable
backgroundTask = [WDBackgroundTask beginBackgroundTaskWithSafeExpirationHandler:^{
backgroundTask = UIBackgroundTaskInvalid;
}];
// your task code here
// ...
backgroundTask = [WDBackgroundTask endBackgroundTaskSafe:backgroundTask];
#import <Foundation/Foundation.h>
@interface WDBackgroundTask : NSObject
+ (UIBackgroundTaskIdentifier) beginBackgroundTaskWithSafeExpirationHandler:(void (^)(void))handler;
+ (UIBackgroundTaskIdentifier) endBackgroundTaskSafe:(UIBackgroundTaskIdentifier)backgroundTaskIdentifier;
@end
#import "WDBackgroundTask.h"
@implementation WDBackgroundTask
+ (UIBackgroundTaskIdentifier) beginBackgroundTaskWithSafeExpirationHandler:(void (^)(void))handler
{
UIBackgroundTaskIdentifier localBackgroundTaskIdentifier = UIBackgroundTaskInvalid;
// block captures the local variable for safety, so it will always end that identifier
localBackgroundTaskIdentifier = [[UIApplication sharedApplication] beginBackgroundTaskWithExpirationHandler:^{
handler();
[[UIApplication sharedApplication] endBackgroundTask:localBackgroundTaskIdentifier];
}];
return localBackgroundTaskIdentifier;
}
+ (UIBackgroundTaskIdentifier) endBackgroundTaskSafe:(UIBackgroundTaskIdentifier)backgroundTaskIdentifier
{
if (backgroundTaskIdentifier != UIBackgroundTaskInvalid)
{
[[UIApplication sharedApplication] endBackgroundTask:backgroundTaskIdentifier];
}
return UIBackgroundTaskInvalid;
}
@end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment