-
Notifications
You must be signed in to change notification settings - Fork 110
/
SDLBackgroundTaskManager.m
68 lines (50 loc) 路 1.88 KB
/
SDLBackgroundTaskManager.m
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
//
// SDLBackgroundTaskManager.m
// SmartDeviceLink
//
// Created by Nicole on 6/25/19.
// Copyright 漏 2019 smartdevicelink. All rights reserved.
//
#import "SDLBackgroundTaskManager.h"
#import "SDLLogMacros.h"
NS_ASSUME_NONNULL_BEGIN
@interface SDLBackgroundTaskManager ()
@property (copy, nonatomic) NSString *backgroundTaskName;
@property (assign, nonatomic) UIBackgroundTaskIdentifier currentBackgroundTaskId;
@end
@implementation SDLBackgroundTaskManager
- (instancetype)initWithBackgroundTaskName:(NSString *)backgroundTaskName {
SDLLogV(@"SDLBackgroundTaskManager init with name %@", backgroundTaskName);
self = [super init];
if (!self) {
return nil;
}
_backgroundTaskName = backgroundTaskName;
return self;
}
- (void)startBackgroundTask {
if (self.currentBackgroundTaskId != UIBackgroundTaskInvalid) {
SDLLogV(@"The %@ background task is already running.", self.backgroundTaskName);
return;
}
__weak typeof(self) weakself = self;
self.currentBackgroundTaskId = [[UIApplication sharedApplication] beginBackgroundTaskWithName:self.backgroundTaskName expirationHandler:^{
SDLLogD(@"The %@ background task expired", self.backgroundTaskName);
[weakself endBackgroundTask];
}];
SDLLogD(@"The %@ background task started with id: %lu", self.backgroundTaskName, (unsigned long)self.currentBackgroundTaskId);
}
- (void)endBackgroundTask {
if (self.currentBackgroundTaskId == UIBackgroundTaskInvalid) {
SDLLogV(@"Background task already ended. Returning...");
return;
}
SDLLogD(@"Ending background task with id: %lu", (unsigned long)self.currentBackgroundTaskId);
[[UIApplication sharedApplication] endBackgroundTask:self.currentBackgroundTaskId];
self.currentBackgroundTaskId = UIBackgroundTaskInvalid;
}
- (void)dealloc {
[self endBackgroundTask];
}
@end
NS_ASSUME_NONNULL_END