-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// nb. backgroundTask is a member variable | |
backgroundTask = [WDBackgroundTask beginBackgroundTaskWithSafeExpirationHandler:^{ | |
backgroundTask = UIBackgroundTaskInvalid; | |
}]; | |
// your task code here | |
// ... | |
backgroundTask = [WDBackgroundTask endBackgroundTaskSafe:backgroundTask]; | |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#import <Foundation/Foundation.h> | |
@interface WDBackgroundTask : NSObject | |
+ (UIBackgroundTaskIdentifier) beginBackgroundTaskWithSafeExpirationHandler:(void (^)(void))handler; | |
+ (UIBackgroundTaskIdentifier) endBackgroundTaskSafe:(UIBackgroundTaskIdentifier)backgroundTaskIdentifier; | |
@end |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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