-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathTJBackgroundTask.m
More file actions
83 lines (71 loc) · 2.06 KB
/
TJBackgroundTask.m
File metadata and controls
83 lines (71 loc) · 2.06 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
//
// TJBackgroundTask.m
// Close-up
//
// Created by Tim Johnsen on 5/26/18.
//
#import "TJBackgroundTask.h"
#import <os/lock.h>
#if defined(__has_attribute) && __has_attribute(objc_direct_members)
__attribute__((objc_direct_members))
#endif
@implementation TJBackgroundTask {
UIBackgroundTaskIdentifier _taskIdentifier;
os_unfair_lock _lock;
}
- (instancetype)init
{
return [self initWithName:nil
expirationHandler:nil];
}
- (instancetype)initWithName:(NSString *)name
{
return [self initWithName:name
expirationHandler:nil];
}
- (instancetype)initWithName:(NSString *const)name expirationHandler:(dispatch_block_t)expirationHandler
{
BOOL check;
if (@available(iOS 13.0, *)) {
check = YES;
} else {
check = [NSThread isMainThread];
}
if (check) {
// Don't start a new background task if fewer than 5 seconds are available.
// https://developer.apple.com/videos/play/wwdc2020/10078/?t=640
// (It's not safe to call this off the main thread on iOS 12)
if ([[UIApplication sharedApplication] backgroundTimeRemaining] < 5.0) {
return nil;
}
}
if (self = [super init]) {
_lock = OS_UNFAIR_LOCK_INIT;
__weak TJBackgroundTask *weakSelf = self;
_taskIdentifier = [[UIApplication sharedApplication] beginBackgroundTaskWithName:name
expirationHandler:^{
if (expirationHandler) {
expirationHandler();
}
__strong TJBackgroundTask *strongSelf = weakSelf;
if (strongSelf) {
[strongSelf endTask];
}
}];
}
return self;
}
- (void)endTask
{
os_unfair_lock_lock(&_lock);
if (_taskIdentifier != UIBackgroundTaskInvalid) {
[[UIApplication sharedApplication] endBackgroundTask:_taskIdentifier];
_taskIdentifier = UIBackgroundTaskInvalid;
}
os_unfair_lock_unlock(&_lock);
}
- (void)dealloc
{
[self endTask];
}
@end