-
Notifications
You must be signed in to change notification settings - Fork 0
/
BIQFileOperator.m
285 lines (231 loc) · 9.36 KB
/
BIQFileOperator.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
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
//
// FileOperator.m
//
// Created by Toma Popov on 1/23/15.
// Copyright (c) 2015 . All rights reserved.
//
#import "FileOperator.h"
#import <UIKit/UIKit.h>
#import "NSError+FileOperator.h"
#import "UserDefaultsManager.h"
const NSUInteger kOneWeekInSeconds = 60 * 60 * 24 * 7;
@interface FileOperator ()
@property (strong, nonatomic) NSOperationQueue *fileLoadQueue;
@property (strong, nonatomic) NSString *cachesDirectoryPath;
@property (strong, nonatomic) NSCache *imageCache;
@end
@implementation FileOperator
static FileOperator *sharedInstance = nil;
+ (instancetype)sharedInstance {
static dispatch_once_t once;
dispatch_once(&once, ^{
sharedInstance = [[self alloc] init];
});
return sharedInstance;
}
- (instancetype)init {
if ((self = [super init])) {
self.fileLoadQueue = [NSOperationQueue new];
self.cachesDirectoryPath = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject];
self.imageCache = [NSCache new];
self.imageCache.countLimit = 10; //not final value
[self performAllFilesCleanUp];
[self setupDirectories];
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(handleMemoryWarningNotification:)
name:UIApplicationDidReceiveMemoryWarningNotification
object:nil];
}
return self;
}
- (NSString *)localFileNameForRemoteURLString:(NSURL *)remoteURL {
if (![remoteURL isKindOfClass:NSURL.class]) {
return nil;
}
NSString *localFileName = [NSString stringWithUTF8String:remoteURL.fileSystemRepresentation];
return [localFileName stringByReplacingOccurrencesOfString:@"/" withString:@"_"];
}
#pragma mark - Public interface
- (void)cachedDataForURL:(NSURL *)URL
isImageLookup:(BOOL)isImageLookup
completionQueue:(NSOperationQueue *)completionQueue
completion:(void (^)(NSData *result, NSError *error))completion {
[self cachedDataForFileName:[self localFileNameForRemoteURLString:URL]
isImageLookup:isImageLookup
completionQueue:completionQueue
completion:completion];
}
- (void)cachedDataForFileName:(NSString *)filename
isImageLookup:(BOOL)isImageLookup
completionQueue:(NSOperationQueue *)completionQueue
completion:(void (^)(NSData *result, NSError *error))completion {
if (!filename.length) {
NSError *err = [NSError errorWithCode:ErrorCodeFileOperation description:@"Missing URL string."];
if (completion) {
[self operationQueue:completionQueue performBlock:^{
completion(nil, err);
}];
}
return;
}
NSBlockOperation *fileLookOp = [NSBlockOperation new];
[fileLookOp addExecutionBlock:^{
NSData *cachedData = [self fileForFilePath:[self localFilePathForFilename:filename]
isImageLookup:isImageLookup];
if (completion) {
if (cachedData) {
[self operationQueue:completionQueue performBlock:^{
completion(cachedData, nil);
}];
} else {
NSError *error = [NSError errorWithCode:ErrorCodeFileOperation description:@"No cached file found."];
[self operationQueue:completionQueue performBlock:^{
completion(nil, error);
}];
}
}
}];
[self.fileLoadQueue addOperation:fileLookOp];
}
- (void)storeData:(NSData *)data
isImageOp:(BOOL)isImageOp
fileName:(NSString *)filename
completionQueue:(NSOperationQueue *)completionQueue
completion:(void (^)(NSError *error))completion {
if (!data || !filename) {
NSError *err = [NSError errorWithCode:ErrorCodeFileOperation description:@"Missing data or URL string."];
if (completion) {
[self operationQueue:completionQueue performBlock:^{
completion(err);
}];
}
return;
}
NSBlockOperation *fileLookOp = [NSBlockOperation new];
[fileLookOp addExecutionBlock:^{
NSString *filePath = [self localFilePathForFilename:filename];
if (![[NSFileManager defaultManager] createFileAtPath:filePath contents:data attributes:nil]) {
NSError *err = [NSError errorWithCode:ErrorCodeFileOperation description:@"Saving failed."];
if (completion) {
[self operationQueue:completionQueue performBlock:^{
completion(err);
}];
}
return;
}
if (isImageOp) {
[self addDataToImageCache:data forFilename:filename];
}
if (completion) {
[self operationQueue:completionQueue performBlock:^{
completion(nil);
}];
}
}];
[self.fileLoadQueue addOperation:fileLookOp];
}
- (void)storeData:(NSData *)data
isImageOp:(BOOL)isImageOp
URL:(NSURL *)URL
completionQueue:(NSOperationQueue *)completionQueue
completion:(void (^)(NSError *error))completion {
[self storeData:data
isImageOp:isImageOp
fileName:[self localFileNameForRemoteURLString:URL]
completionQueue:completionQueue
completion:completion];
}
- (void)removeCachedDataForEntities:(NSArray *)entities
ofClassType:(Class)classType
completionQueue:(NSOperationQueue *)completionQueue
completion:(void (^)(NSError *error))completion {}
- (void)removeCachedDataForFilename:(NSString *)filename
completionQueue:(NSOperationQueue *)completionQueue
completion:(void (^)(NSError *error))completion {
NSBlockOperation *fileLookOp = [NSBlockOperation new];
[fileLookOp addExecutionBlock:^{
NSString *filePath = [self localFilePathForFilename:filename];
NSFileManager *fileManager = [NSFileManager defaultManager];
NSError *fileOpErr;
BOOL success = [fileManager removeItemAtPath:filePath error:&fileOpErr];
if (!success) {
//failure
}
if (completion) {
[self operationQueue:completionQueue performBlock:^{
completion(nil);
}];
}
}];
[self.fileLoadQueue addOperation:fileLookOp];
}
- (void)performAllFilesCleanUp {
if (![UserDefaultsManager.sharedManager timeOfLastLocalFileCleanUp]) {
[UserDefaultsManager.sharedManager setTimeOfLastLocalFileCleanUp:NSDate.date];
} else if ([NSDate.date timeIntervalSinceDate:[UserDefaultsManager.sharedManager timeOfLastLocalFileCleanUp]] >= kOneWeekInSeconds) {
if ([[NSFileManager defaultManager] removeItemAtPath:self.cachesDirectoryPath error:nil]) {
[UserDefaultsManager.sharedManager setTimeOfLastLocalFileCleanUp:NSDate.date];
}
}
}
#pragma mark - Local Image Retrieval
- (NSData *)fileForFilePath:(NSString *)filePath isImageLookup:(BOOL)imageLookup {
NSData *result = nil;
if (filePath) {
//check in virtual cache
if (imageLookup) {
result = [self.imageCache objectForKey:[filePath lastPathComponent]];
}
if (!result) {
//check in local storage
if ([[NSFileManager defaultManager] fileExistsAtPath:filePath]) {
result = [NSData dataWithContentsOfFile:filePath];
[self addDataToImageCache:result forFilename:[filePath lastPathComponent]];
}
}
}
return result;
}
#pragma mark - Image Local Path Utilities
- (NSString *)localFilePathForURL:(NSURL *)url {
return [self localFilePathForFilename:[self localFileNameForRemoteURLString:url]];
}
- (NSString *)folderInCachesWithName:(NSString *)folderName {
NSString *result = [self.cachesDirectoryPath stringByAppendingPathComponent:folderName];
return result;
}
- (NSString *)cachesDirectoryPath {
return [self folderInCachesWithName:@"cached_files"];
}
- (NSString *)localFilePathForFilename:(NSString *)filename {
return filename ? [self.cachesDirectoryPath stringByAppendingPathComponent:filename] : nil;
}
- (void)addDataToImageCache:(NSData *)data forFilename:(NSString *)filename {
//add to virutal cache
[self.imageCache setObject:data forKey:filename];
}
#pragma mark - Directory Setup
- (void)setupDirectories {
NSFileManager *manager = [NSFileManager defaultManager];
if (![manager fileExistsAtPath:self.cachesDirectoryPath]) {
[manager createDirectoryAtPath:self.cachesDirectoryPath
withIntermediateDirectories:YES
attributes:nil error:NULL];
}
}
#pragma mark - System notifications
- (void)handleMemoryWarningNotification:(NSNotification *)aNotification {
[self.imageCache removeAllObjects];
}
#pragma mark - Dispatch on queue
- (void)operationQueue:(NSOperationQueue *)operationQueue performBlock:(void (^)(void))block {
if (block) {
if (operationQueue && operationQueue != NSOperationQueue.currentQueue) {
[operationQueue addOperationWithBlock:block];
}
else {
block();
}
}
}
@end