Create a gist now

Instantly share code, notes, and snippets.

@WilliamDenniss /Example.m Secret
Last active Dec 16, 2015

What would you like to do?
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