-
Notifications
You must be signed in to change notification settings - Fork 13
/
Copy pathICACloud.m
630 lines (517 loc) · 24.6 KB
/
ICACloud.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
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
//
// ICACloud
// iCloud Access
//
// Created by Drew McCormack on 18/01/14.
// Copyright (c) 2014 Drew McCormack. All rights reserved.
//
#import "ICACloud.h"
NSString *ICAException = @"ICAException";
NSString *ICAErrorDomain = @"ICAErrorDomain";
@interface ICACloudFile ()
@property (readwrite, copy) NSString *path;
@property (readwrite, copy) NSString *name;
@property (readwrite) NSDictionary *fileAttributes;
@end
@implementation ICACloudFile
@synthesize path = path;
@synthesize name = name;
@synthesize fileAttributes = fileAttributes;
@end
@implementation ICACloud {
NSFileManager *fileManager;
NSURL *rootDirectoryURL;
NSMetadataQuery *metadataQuery;
NSOperationQueue *operationQueue;
NSString *ubiquityContainerIdentifier;
dispatch_queue_t timeOutQueue;
id ubiquityIdentityObserver;
}
@synthesize rootDirectoryPath = rootDirectoryPath;
// Designated
- (instancetype)initWithUbiquityContainerIdentifier:(NSString *)newIdentifier rootDirectoryPath:(NSString *)newPath
{
self = [super init];
if (self) {
fileManager = [[NSFileManager alloc] init];
rootDirectoryPath = [newPath copy] ? : @"";
operationQueue = [[NSOperationQueue alloc] init];
operationQueue.maxConcurrentOperationCount = 1;
timeOutQueue = dispatch_queue_create("com.mentalfaculty.cloudaccess.queue.icloudtimeout", DISPATCH_QUEUE_SERIAL);
rootDirectoryURL = nil;
metadataQuery = nil;
ubiquityContainerIdentifier = [newIdentifier copy];
ubiquityIdentityObserver = nil;
[self performInitialPreparation:NULL];
}
return self;
}
- (instancetype)initWithUbiquityContainerIdentifier:(NSString *)newIdentifier
{
return [self initWithUbiquityContainerIdentifier:newIdentifier rootDirectoryPath:nil];
}
- (instancetype)init
{
@throw [NSException exceptionWithName:ICAException reason:@"iCloud initializer requires container identifier" userInfo:nil];
return nil;
}
- (void)dealloc
{
[self removeUbiquityContainerNotificationObservers];
[self stopMonitoring];
[operationQueue cancelAllOperations];
}
#pragma mark - User Identity
- (id <NSObject, NSCoding, NSCopying>)identityToken
{
return [fileManager ubiquityIdentityToken];
}
#pragma mark - Initial Preparation
- (void)performInitialPreparation:(void(^)(NSError *error))completion
{
if (fileManager.ubiquityIdentityToken) {
[self setupRootDirectory:^(NSError *error) {
[self startMonitoringMetadata];
[self addUbiquityContainerNotificationObservers];
dispatch_async(dispatch_get_main_queue(), ^{
if (completion) completion(error);
});
}];
}
else {
[self addUbiquityContainerNotificationObservers];
dispatch_async(dispatch_get_main_queue(), ^{
if (completion) completion(nil);
});
}
}
#pragma mark - Root Directory
- (void)setupRootDirectory:(void(^)(NSError *error))completion
{
[operationQueue addOperationWithBlock:^{
NSURL *newURL = [fileManager URLForUbiquityContainerIdentifier:ubiquityContainerIdentifier];
newURL = [newURL URLByAppendingPathComponent:rootDirectoryPath];
rootDirectoryURL = newURL;
if (!rootDirectoryURL) {
NSError *error = [NSError errorWithDomain:ICAErrorDomain code:ICAErrorCodeFileAccessFailed userInfo:@{NSLocalizedDescriptionKey : @"Could not retrieve URLForUbiquityContainerIdentifier. Check container id for iCloud."}];
[self dispatchCompletion:completion withError:error];
return;
}
NSError *error = nil;
__block BOOL fileExistsAtPath = NO;
__block BOOL existingFileIsDirectory = NO;
NSFileCoordinator *coordinator = [[NSFileCoordinator alloc] initWithFilePresenter:nil];
[coordinator coordinateReadingItemAtURL:rootDirectoryURL options:NSFileCoordinatorReadingWithoutChanges error:&error byAccessor:^(NSURL *newURL) {
fileExistsAtPath = [fileManager fileExistsAtPath:newURL.path isDirectory:&existingFileIsDirectory];
}];
if (error) {
[self dispatchCompletion:completion withError:error];
return;
}
if (!fileExistsAtPath) {
[coordinator coordinateWritingItemAtURL:rootDirectoryURL options:0 error:&error byAccessor:^(NSURL *newURL) {
[fileManager createDirectoryAtURL:newURL withIntermediateDirectories:YES attributes:nil error:NULL];
}];
}
else if (fileExistsAtPath && !existingFileIsDirectory) {
[coordinator coordinateWritingItemAtURL:rootDirectoryURL options:NSFileCoordinatorWritingForReplacing error:&error byAccessor:^(NSURL *newURL) {
[fileManager removeItemAtURL:newURL error:NULL];
[fileManager createDirectoryAtURL:newURL withIntermediateDirectories:YES attributes:nil error:NULL];
}];
}
[self dispatchCompletion:completion withError:error];
}];
}
- (void)dispatchCompletion:(void(^)(NSError *error))completion withError:(NSError *)error
{
dispatch_sync(dispatch_get_main_queue(), ^{
if (completion) completion(error);
});
}
- (NSString *)fullPathForPath:(NSString *)path
{
return [rootDirectoryURL.path stringByAppendingPathComponent:path];
}
#pragma mark - Notifications
- (void)removeUbiquityContainerNotificationObservers
{
[[NSNotificationCenter defaultCenter] removeObserver:ubiquityIdentityObserver];
ubiquityIdentityObserver = nil;
}
- (void)addUbiquityContainerNotificationObservers
{
[self removeUbiquityContainerNotificationObservers];
__weak typeof(self) weakSelf = self;
ubiquityIdentityObserver = [[NSNotificationCenter defaultCenter] addObserverForName:NSUbiquityIdentityDidChangeNotification object:nil queue:[NSOperationQueue mainQueue] usingBlock:^(NSNotification *note) {
__strong typeof(weakSelf) strongSelf = weakSelf;
[strongSelf stopMonitoring];
[strongSelf willChangeValueForKey:@"identityToken"];
[strongSelf didChangeValueForKey:@"identityToken"];
[self connect];
}];
}
#pragma mark - Connection
- (BOOL)isConnected
{
return fileManager.ubiquityIdentityToken != nil;
}
- (void)connect
{
BOOL loggedIn = fileManager.ubiquityIdentityToken != nil;
if (loggedIn) [self performInitialPreparation:NULL];
}
#pragma mark - Metadata Query to download new files
- (void)startMonitoringMetadata
{
[self stopMonitoring];
if (!rootDirectoryURL) return;
// Determine downloading key and set the appropriate predicate. This is OS dependent.
NSPredicate *metadataPredicate = nil;
#if (__IPHONE_OS_VERSION_MIN_REQUIRED < 70000) && (__MAC_OS_X_VERSION_MIN_REQUIRED < 1090)
metadataPredicate = [NSPredicate predicateWithFormat:@"%K = FALSE AND %K = FALSE AND %K BEGINSWITH %@",
NSMetadataUbiquitousItemIsDownloadedKey, NSMetadataUbiquitousItemIsDownloadingKey, NSMetadataItemPathKey, rootDirectoryURL.path];
#else
metadataPredicate = [NSPredicate predicateWithFormat:@"%K != %@ AND %K = FALSE AND %K BEGINSWITH %@",
NSMetadataUbiquitousItemDownloadingStatusKey, NSMetadataUbiquitousItemDownloadingStatusCurrent, NSMetadataUbiquitousItemIsDownloadingKey, NSMetadataItemPathKey, rootDirectoryURL.path];
#endif
metadataQuery = [[NSMetadataQuery alloc] init];
metadataQuery.notificationBatchingInterval = 10.0;
metadataQuery.searchScopes = [NSArray arrayWithObject:NSMetadataQueryUbiquitousDataScope];
metadataQuery.predicate = metadataPredicate;
NSNotificationCenter *notifationCenter = [NSNotificationCenter defaultCenter];
[notifationCenter addObserver:self selector:@selector(initiateDownloads:) name:NSMetadataQueryDidFinishGatheringNotification object:metadataQuery];
[notifationCenter addObserver:self selector:@selector(initiateDownloads:) name:NSMetadataQueryDidUpdateNotification object:metadataQuery];
[metadataQuery startQuery];
}
- (void)stopMonitoring
{
if (!metadataQuery) return;
[metadataQuery disableUpdates];
[metadataQuery stopQuery];
[[NSNotificationCenter defaultCenter] removeObserver:self name:NSMetadataQueryDidFinishGatheringNotification object:metadataQuery];
[[NSNotificationCenter defaultCenter] removeObserver:self name:NSMetadataQueryDidUpdateNotification object:metadataQuery];
metadataQuery = nil;
}
- (void)initiateDownloads:(NSNotification *)notif
{
[metadataQuery disableUpdates];
NSUInteger count = [metadataQuery resultCount];
dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0);
for ( NSUInteger i = 0; i < count; i++ ) {
@autoreleasepool {
NSMetadataItem *item = [metadataQuery resultAtIndex:i];
[self resolveConflictsForMetadataItem:item];
NSURL *url = [item valueForAttribute:NSMetadataItemURLKey];
dispatch_async(queue, ^{
NSError *error;
[fileManager startDownloadingUbiquitousItemAtURL:url error:&error];
});
}
}
[metadataQuery enableUpdates];
}
- (void)resolveConflictsForMetadataItem:(NSMetadataItem *)item
{
NSURL *fileURL = [item valueForAttribute:NSMetadataItemURLKey];
BOOL inConflict = [[item valueForAttribute:NSMetadataUbiquitousItemHasUnresolvedConflictsKey] boolValue];
if (inConflict) {
NSFileCoordinator *coordinator = [[NSFileCoordinator alloc] initWithFilePresenter:nil];
__block BOOL coordinatorExecuted = NO;
__block BOOL timedOut = NO;
dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, ICAFileCoordinatorTimeOut * NSEC_PER_SEC);
dispatch_after(popTime, timeOutQueue, ^{
if (!coordinatorExecuted) {
timedOut = YES;
[coordinator cancel];
}
});
NSError *coordinatorError = nil;
[coordinator coordinateWritingItemAtURL:fileURL options:NSFileCoordinatorWritingForDeleting error:&coordinatorError byAccessor:^(NSURL *newURL) {
dispatch_sync(timeOutQueue, ^{ coordinatorExecuted = YES; });
if (timedOut) return;
[NSFileVersion removeOtherVersionsOfItemAtURL:newURL error:nil];
}];
if (timedOut || coordinatorError) return;
NSArray *conflictVersions = [NSFileVersion unresolvedConflictVersionsOfItemAtURL:fileURL];
for (NSFileVersion *fileVersion in conflictVersions) {
fileVersion.resolved = YES;
}
}
}
#pragma mark - File Operations
static const NSTimeInterval ICAFileCoordinatorTimeOut = 10.0;
- (NSError *)specializedErrorForCocoaError:(NSError *)cocoaError
{
NSError *error = cocoaError;
if ([cocoaError.domain isEqualToString:NSCocoaErrorDomain] && cocoaError.code == NSUserCancelledError) {
error = [NSError errorWithDomain:ICAErrorDomain code:ICAErrorCodeFileCoordinatorTimedOut userInfo:nil];
}
return error;
}
- (NSError *)notConnectedError
{
NSError *error = [NSError errorWithDomain:ICAErrorDomain code:ICAErrorCodeConnectionError userInfo:@{NSLocalizedDescriptionKey : @"Attempted to access iCloud when not connected."}];
return error;
}
- (void)fileExistsAtPath:(NSString *)path completion:(void(^)(BOOL exists, BOOL isDirectory, NSError *error))block
{
[operationQueue addOperationWithBlock:^{
if (!self.isConnected) {
dispatch_async(dispatch_get_main_queue(), ^{
if (block) block(NO, NO, [self notConnectedError]);
});
return;
}
NSError *fileCoordinatorError = nil;
__block NSError *timeoutError = nil;
__block BOOL coordinatorExecuted = NO;
__block BOOL isDirectory = NO;
__block BOOL exists = NO;
NSFileCoordinator *coordinator = [[NSFileCoordinator alloc] initWithFilePresenter:nil];
dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, ICAFileCoordinatorTimeOut * NSEC_PER_SEC);
dispatch_after(popTime, timeOutQueue, ^{
if (!coordinatorExecuted) {
[coordinator cancel];
timeoutError = [NSError errorWithDomain:ICAErrorDomain code:ICAErrorCodeFileCoordinatorTimedOut userInfo:nil];
}
});
NSURL *url = [NSURL fileURLWithPath:[self fullPathForPath:path]];
[coordinator coordinateReadingItemAtURL:url options:0 error:&fileCoordinatorError byAccessor:^(NSURL *newURL) {
dispatch_sync(timeOutQueue, ^{ coordinatorExecuted = YES; });
if (timeoutError) return;
exists = [fileManager fileExistsAtPath:newURL.path isDirectory:&isDirectory];
}];
NSError *error = fileCoordinatorError ? : timeoutError ? : nil;
error = [self specializedErrorForCocoaError:error];
dispatch_async(dispatch_get_main_queue(), ^{
if (block) block(exists, isDirectory, error);
});
}];
}
- (void)contentsOfDirectoryAtPath:(NSString *)path completion:(void(^)(NSArray *contents, NSError *error))block
{
[operationQueue addOperationWithBlock:^{
if (!self.isConnected) {
dispatch_async(dispatch_get_main_queue(), ^{
if (block) block(nil, [self notConnectedError]);
});
return;
}
NSError *fileCoordinatorError = nil;
__block NSError *timeoutError = nil;
__block NSError *fileManagerError = nil;
__block BOOL coordinatorExecuted = NO;
NSFileCoordinator *coordinator = [[NSFileCoordinator alloc] initWithFilePresenter:nil];
dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, ICAFileCoordinatorTimeOut * NSEC_PER_SEC);
dispatch_after(popTime, timeOutQueue, ^{
if (!coordinatorExecuted) {
[coordinator cancel];
timeoutError = [NSError errorWithDomain:ICAErrorDomain code:ICAErrorCodeFileCoordinatorTimedOut userInfo:nil];
}
});
__block NSArray *contents = nil;
NSURL *url = [NSURL fileURLWithPath:[self fullPathForPath:path]];
[coordinator coordinateReadingItemAtURL:url options:0 error:&fileCoordinatorError byAccessor:^(NSURL *newURL) {
dispatch_sync(timeOutQueue, ^{ coordinatorExecuted = YES; });
if (timeoutError) return;
NSDirectoryEnumerator *dirEnum = [fileManager enumeratorAtPath:[self fullPathForPath:path]];
if (!dirEnum) fileManagerError = [NSError errorWithDomain:ICAErrorDomain code:ICAErrorCodeFileAccessFailed userInfo:nil];
NSString *filename;
NSMutableArray *mutableContents = [[NSMutableArray alloc] init];
while ((filename = [dirEnum nextObject])) {
if ([@[@".DS_Store", @".", @".."] containsObject:filename]) continue;
ICACloudFile *file = [ICACloudFile new];
file.name = filename;
file.path = [path stringByAppendingPathComponent:filename];;
file.fileAttributes = [dirEnum.fileAttributes copy];
[mutableContents addObject:file];
if ([dirEnum.fileAttributes.fileType isEqualToString:NSFileTypeDirectory]) {
[dirEnum skipDescendants];
}
}
if (!fileManagerError) contents = mutableContents;
}];
NSError *error = fileCoordinatorError ? : timeoutError ? : fileManagerError ? : nil;
error = [self specializedErrorForCocoaError:error];
dispatch_async(dispatch_get_main_queue(), ^{
if (block) block(contents, error);
});
}];
}
- (void)createDirectoryAtPath:(NSString *)path completion:(void(^)(NSError *error))block
{
[operationQueue addOperationWithBlock:^{
if (!self.isConnected) {
dispatch_async(dispatch_get_main_queue(), ^{
if (block) block([self notConnectedError]);
});
return;
}
NSError *fileCoordinatorError = nil;
__block NSError *timeoutError = nil;
__block NSError *fileManagerError = nil;
__block BOOL coordinatorExecuted = NO;
NSFileCoordinator *coordinator = [[NSFileCoordinator alloc] initWithFilePresenter:nil];
dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, ICAFileCoordinatorTimeOut * NSEC_PER_SEC);
dispatch_after(popTime, timeOutQueue, ^{
if (!coordinatorExecuted) {
[coordinator cancel];
timeoutError = [NSError errorWithDomain:ICAErrorDomain code:ICAErrorCodeFileCoordinatorTimedOut userInfo:nil];
}
});
NSURL *url = [NSURL fileURLWithPath:[self fullPathForPath:path]];
[coordinator coordinateWritingItemAtURL:url options:0 error:&fileCoordinatorError byAccessor:^(NSURL *newURL) {
dispatch_sync(timeOutQueue, ^{ coordinatorExecuted = YES; });
if (timeoutError) return;
[fileManager createDirectoryAtPath:newURL.path withIntermediateDirectories:YES attributes:nil error:&fileManagerError];
}];
NSError *error = fileCoordinatorError ? : timeoutError ? : fileManagerError ? : nil;
error = [self specializedErrorForCocoaError:error];
dispatch_async(dispatch_get_main_queue(), ^{
if (block) block(error);
});
}];
}
- (void)removeItemAtPath:(NSString *)path completion:(void(^)(NSError *error))block
{
[operationQueue addOperationWithBlock:^{
if (!self.isConnected) {
dispatch_async(dispatch_get_main_queue(), ^{
if (block) block([self notConnectedError]);
});
return;
}
NSError *fileCoordinatorError = nil;
__block NSError *timeoutError = nil;
__block NSError *fileManagerError = nil;
__block BOOL coordinatorExecuted = NO;
NSFileCoordinator *coordinator = [[NSFileCoordinator alloc] initWithFilePresenter:nil];
dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, ICAFileCoordinatorTimeOut * NSEC_PER_SEC);
dispatch_after(popTime, timeOutQueue, ^{
if (!coordinatorExecuted) {
[coordinator cancel];
timeoutError = [NSError errorWithDomain:ICAErrorDomain code:ICAErrorCodeFileCoordinatorTimedOut userInfo:nil];
}
});
NSURL *url = [NSURL fileURLWithPath:[self fullPathForPath:path]];
[coordinator coordinateWritingItemAtURL:url options:NSFileCoordinatorWritingForDeleting error:&fileCoordinatorError byAccessor:^(NSURL *newURL) {
dispatch_sync(timeOutQueue, ^{ coordinatorExecuted = YES; });
if (timeoutError) return;
[fileManager removeItemAtPath:newURL.path error:&fileManagerError];
}];
NSError *error = fileCoordinatorError ? : timeoutError ? : fileManagerError ? : nil;
error = [self specializedErrorForCocoaError:error];
dispatch_async(dispatch_get_main_queue(), ^{
if (block) block(error);
});
}];
}
- (NSString *)temporaryDirectory
{
static NSString *tempDir = nil;
if (!tempDir) {
tempDir = [NSTemporaryDirectory() stringByAppendingString:@"ICACloudTempFiles"];
BOOL isDir;
if (![fileManager fileExistsAtPath:tempDir isDirectory:&isDir] || !isDir) {
NSError *error;
[fileManager removeItemAtPath:tempDir error:NULL];
if (![fileManager createDirectoryAtPath:tempDir withIntermediateDirectories:YES attributes:nil error:&error]) {
tempDir = nil;
NSLog(@"Error creating temp dir for ICACloud: %@", error);
}
}
}
return tempDir;
}
- (void)uploadData:(NSData *)data toPath:(NSString *)toPath completion:(void(^)(NSError *error))completion
{
NSString *tempFile = [[self temporaryDirectory] stringByAppendingPathComponent:[[NSProcessInfo processInfo] globallyUniqueString]];
[data writeToFile:tempFile atomically:NO];
[self uploadLocalFile:tempFile toPath:toPath completion:^(NSError *error) {
[fileManager removeItemAtPath:tempFile error:NULL];
if (completion) completion(error);
}];
}
- (void)uploadLocalFile:(NSString *)fromPath toPath:(NSString *)toPath completion:(void(^)(NSError *error))block
{
[operationQueue addOperationWithBlock:^{
if (!self.isConnected) {
dispatch_async(dispatch_get_main_queue(), ^{
if (block) block([self notConnectedError]);
});
return;
}
NSError *fileCoordinatorError = nil;
__block NSError *timeoutError = nil;
__block NSError *fileManagerError = nil;
__block BOOL coordinatorExecuted = NO;
NSFileCoordinator *coordinator = [[NSFileCoordinator alloc] initWithFilePresenter:nil];
dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, ICAFileCoordinatorTimeOut * NSEC_PER_SEC);
dispatch_after(popTime, timeOutQueue, ^{
if (!coordinatorExecuted) {
[coordinator cancel];
timeoutError = [NSError errorWithDomain:ICAErrorDomain code:ICAErrorCodeFileCoordinatorTimedOut userInfo:nil];
}
});
NSURL *fromURL = [NSURL fileURLWithPath:fromPath];
NSURL *toURL = [NSURL fileURLWithPath:[self fullPathForPath:toPath]];
[coordinator coordinateReadingItemAtURL:fromURL options:0 writingItemAtURL:toURL options:NSFileCoordinatorWritingForReplacing error:&fileCoordinatorError byAccessor:^(NSURL *newReadingURL, NSURL *newWritingURL) {
dispatch_sync(timeOutQueue, ^{ coordinatorExecuted = YES; });
if (timeoutError) return;
[fileManager removeItemAtPath:newWritingURL.path error:NULL];
[fileManager copyItemAtPath:newReadingURL.path toPath:newWritingURL.path error:&fileManagerError];
}];
NSError *error = fileCoordinatorError ? : timeoutError ? : fileManagerError ? : nil;
error = [self specializedErrorForCocoaError:error];
dispatch_async(dispatch_get_main_queue(), ^{
if (block) block(error);
});
}];
}
- (void)downloadDataFromPath:(NSString *)fromPath completion:(void(^)(NSData *data, NSError *error))completion
{
NSString *tempFile = [[self temporaryDirectory] stringByAppendingPathComponent:[[NSProcessInfo processInfo] globallyUniqueString]];
[self downloadFromPath:fromPath toLocalFile:tempFile completion:^(NSError *error) {
NSData *data = nil;
if (!error) data = [NSData dataWithContentsOfFile:tempFile];
[fileManager removeItemAtPath:tempFile error:NULL];
if (completion) completion(data, error);
}];
}
- (void)downloadFromPath:(NSString *)fromPath toLocalFile:(NSString *)toPath completion:(void(^)(NSError *error))block
{
[operationQueue addOperationWithBlock:^{
if (!self.isConnected) {
dispatch_async(dispatch_get_main_queue(), ^{
if (block) block([self notConnectedError]);
});
return;
}
NSError *fileCoordinatorError = nil;
__block NSError *timeoutError = nil;
__block NSError *fileManagerError = nil;
__block BOOL coordinatorExecuted = NO;
NSFileCoordinator *coordinator = [[NSFileCoordinator alloc] initWithFilePresenter:nil];
dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, ICAFileCoordinatorTimeOut * NSEC_PER_SEC);
dispatch_after(popTime, timeOutQueue, ^{
if (!coordinatorExecuted) {
[coordinator cancel];
timeoutError = [NSError errorWithDomain:ICAErrorDomain code:ICAErrorCodeFileCoordinatorTimedOut userInfo:nil];
}
});
NSURL *fromURL = [NSURL fileURLWithPath:[self fullPathForPath:fromPath]];
NSURL *toURL = [NSURL fileURLWithPath:toPath];
[coordinator coordinateReadingItemAtURL:fromURL options:0 writingItemAtURL:toURL options:NSFileCoordinatorWritingForReplacing error:&fileCoordinatorError byAccessor:^(NSURL *newReadingURL, NSURL *newWritingURL) {
dispatch_sync(timeOutQueue, ^{ coordinatorExecuted = YES; });
if (timeoutError) return;
[fileManager removeItemAtPath:newWritingURL.path error:NULL];
[fileManager copyItemAtPath:newReadingURL.path toPath:newWritingURL.path error:&fileManagerError];
}];
NSError *error = fileCoordinatorError ? : timeoutError ? : fileManagerError ? : nil;
error = [self specializedErrorForCocoaError:error];
dispatch_async(dispatch_get_main_queue(), ^{
if (block) block(error);
});
}];
}
@end