Newer
Older
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
//
// HCPUpdateLoader.m
//
// Created by Nikolay Demyankov on 11.08.15.
//
#import "HCPUpdateLoader.h"
#import "HCPUpdateLoaderWorker.h"
#import "HCPUpdateInstaller.h"
#import "NSError+HCPExtension.h"
@interface HCPUpdateLoader() {
__block BOOL _isExecuting;
}
@end
@implementation HCPUpdateLoader
#pragma mark Public API
+ (HCPUpdateLoader *)sharedInstance {
static HCPUpdateLoader *sharedInstance = nil;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
sharedInstance = [[self alloc] init];
});
return sharedInstance;
}
- (BOOL)isDownloadInProgress {
return _isExecuting;
}
- (BOOL)executeDownloadRequest:(HCPUpdateRequest *)request error:(NSError **)error {
if (_isExecuting) {
*error = [NSError errorWithCode:kHCPDownloadAlreadyInProgressErrorCode
description:@"Download already in progress. Please, wait for it to finish."];
return NO;
}
// if installing - don't start the task.
if ([HCPUpdateInstaller sharedInstance].isInstallationInProgress) {
*error = [NSError errorWithCode:kHCPCantDownloadUpdateWhileInstallationInProgressErrorCode
description:@"Installation is in progress, can't launch the download task. Please, wait for it to finish."];
return NO;
}
id<HCPWorker> task = [[HCPUpdateLoaderWorker alloc] initWithRequest:request];
[self executeTask:task];
return YES;
}
#pragma mark Private API
- (void)executeTask:(id<HCPWorker>)task {
_isExecuting = YES;
// execute in background, so the callbacks don't block main thread
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
[task runWithComplitionBlock:^{
_isExecuting = NO;
}];
});
}
@end