-
Notifications
You must be signed in to change notification settings - Fork 0
/
UbiquityStoreManager.m
executable file
·2345 lines (1868 loc) · 97.5 KB
/
UbiquityStoreManager.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
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/**
* Copyright 2012, Maarten Billemont (http://www.lhunath.com, lhunath@lyndir.com)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* @author Maarten Billemont <lhunath@lyndir.com>
* @license Apache License, Version 2.0
*/
//
// UbiquityStoreManager.m
// UbiquityStoreManager
//
#import "UbiquityStoreManager.h"
#import "JRSwizzle.h"
#import "NSError+UbiquityStoreManager.h"
#if TARGET_OS_IPHONE
#import <UIKit/UIKit.h>
#else
#import <Cocoa/Cocoa.h>
#endif
#define IfOut(__out, __value) ({ __typeof__(*__out) __var = __value; if (__out) { *__out = __var; }; __var; })
NSString *const USMStoreWillChangeNotification = @"USMStoreWillChangeNotification";
NSString *const USMStoreDidChangeNotification = @"USMStoreDidChangeNotification";
NSString *const USMStoreDidImportChangesNotification = @"USMStoreDidImportChangesNotification";
NSString *const USMCloudEnabledKey = @"USMCloudEnabledKey";
NSString *const USMCloudVersionKey = @"USMCloudVersionKey";
NSString *const USMCloudCurrentKey = @"USMCloudCurrentKey";
NSString *const USMCloudUUIDKey = @"USMCloudUUIDKey";
NSString *const USMCloudContentName = @"UbiquityStore";
NSString *const USMCloudStoreDirectory = @"CloudStore";
NSString *const USMCloudStoreMigrationSource = @"MigrationSource.sqlite";
NSString *const USMCloudContentDirectory = @"CloudLogs";
NSString *const USMCloudContentStoreUUID = @"StoreUUID";
NSString *const USMCloudContentCorruptedUUID = @"CorruptedUUID";
extern NSString *NSStringFromUSMCause(UbiquityStoreErrorCause cause) {
switch (cause) {
case UbiquityStoreErrorCauseNoError:
return @"UbiquityStoreErrorCauseNoError";
case UbiquityStoreErrorCauseDeleteStore:
return @"UbiquityStoreErrorCauseDeleteStore";
case UbiquityStoreErrorCauseCreateStorePath:
return @"UbiquityStoreErrorCauseCreateStorePath";
case UbiquityStoreErrorCauseClearStore:
return @"UbiquityStoreErrorCauseClearStore";
case UbiquityStoreErrorCauseOpenActiveStore:
return @"UbiquityStoreErrorCauseOpenActiveStore";
case UbiquityStoreErrorCauseOpenSeedStore:
return @"UbiquityStoreErrorCauseOpenSeedStore";
case UbiquityStoreErrorCauseSeedStore:
return @"UbiquityStoreErrorCauseSeedStore";
case UbiquityStoreErrorCauseImportChanges:
return @"UbiquityStoreErrorCauseImportChanges";
case UbiquityStoreErrorCauseConfirmActiveStore:
return @"UbiquityStoreErrorCauseConfirmActiveStore";
case UbiquityStoreErrorCauseCorruptActiveStore:
return @"UbiquityStoreErrorCauseCorruptActiveStore";
case UbiquityStoreErrorCauseEnumerateStores:
return @"UbiquityStoreErrorCauseEnumerateStores";
}
return [NSString stringWithFormat:@"UnsupportedCause:%d", cause];
}
/** USMFilePresenter monitors a file for NSFilePresenter related changes. */
@interface USMFilePresenter : NSObject<NSFilePresenter>
@property(nonatomic, weak, readonly) UbiquityStoreManager *delegate;
@property(nonatomic, strong, readonly) NSFileCoordinator *coordinator;
- (id)initWithURL:(NSURL *)presentedItemURL delegate:(UbiquityStoreManager *)delegate;
- (void)start;
- (void)stop;
@end
/** USMFileContentPresenter extends USMFilePresenter to add metadata change monitoring. */
@interface USMFileContentPresenter : USMFilePresenter
@property(nonatomic, strong) NSMetadataQuery *query;
- (void)handleConflicts;
@end
/** USMLocalStoreFilePresenter monitors our active store file. */
@interface USMLocalStoreFilePresenter : USMFilePresenter
- (id)initWithUSM:(UbiquityStoreManager *)manager;
@end
/** USMLocalStoreFilePresenter monitors the file that contains the active store UUID.
* Changes to this file mean the active store has changed and we need to load the new store.
*/
@interface USMStoreUUIDPresenter : USMFileContentPresenter
- (id)initWithUSM:(UbiquityStoreManager *)manager;
@end
/** USMLocalStoreFilePresenter monitors the file that contains the corrupted store UUID.
* Changes to this file mean a device has detected cloud corruption and we try to fix it.
*/
@interface USMCorruptedUUIDPresenter : USMFileContentPresenter
- (id)initWithUSM:(UbiquityStoreManager *)manager;
@end
@interface UbiquityStoreManager()
@property(nonatomic, copy) NSString *contentName;
@property(nonatomic, strong) NSManagedObjectModel *model;
@property(nonatomic, copy) NSString *containerIdentifier;
@property(nonatomic, copy) NSDictionary *storeOptions;
@property(nonatomic, readonly) NSString *storeUUID;
@property(nonatomic, strong) NSString *tentativeStoreUUID;
@property(nonatomic, strong) NSOperationQueue *persistentStorageQueue;
@property(nonatomic, readonly) NSPersistentStoreCoordinator *persistentStoreCoordinator;
@property(nonatomic, strong) id<NSObject, NSCopying, NSCoding> currentIdentityToken;
@property(nonatomic, strong) NSURL *migrationStoreURL;
@property(nonatomic) BOOL attemptCloudRecovery;
@property(nonatomic) NSString *localCloudStoreCorruptedUUID;
@property(nonatomic) NSString *activeCloudStoreUUID;
@property(nonatomic) BOOL cloudWasEnabled;
@property(nonatomic, strong) USMLocalStoreFilePresenter *storeFilePresenter;
@property(nonatomic, strong) USMStoreUUIDPresenter *storeUUIDPresenter;
@property(nonatomic, strong) USMCorruptedUUIDPresenter *corruptedUUIDPresenter;
@property(nonatomic, assign) BOOL cloudAvailable;
@property(nonatomic, strong) NSBlockOperation *finishedLoadingOperation;
@end
@implementation UbiquityStoreManager {
NSPersistentStoreCoordinator *_persistentStoreCoordinator;
}
+ (void)initialize {
if (![self respondsToSelector:@selector(jr_swizzleMethod:withMethod:error:)]) {
MyLog( @"UbiquityStoreManager: Warning: JRSwizzle not present, won't be able to detect desync issues." );
return;
}
NSError *error = nil;
if (![NSError jr_swizzleMethod:@selector(initWithDomain:code:userInfo:)
withMethod:@selector(init_USM_WithDomain:code:userInfo:)
error:&error])
MyLog( @"UbiquityStoreManager: Warning: Failed to swizzle, won't be able to detect desync issues. Cause: %@", error );
}
- (id)initWithDelegate:(id<UbiquityStoreManagerDelegate>)delegate {
return [self initStoreNamed:nil withManagedObjectModel:nil localStoreURL:nil containerIdentifier:nil
storeConfiguration:nil storeOptions:nil delegate:delegate];
}
- (id)initStoreNamed:(NSString *)contentName withManagedObjectModel:(NSManagedObjectModel *)model localStoreURL:(NSURL *)localStoreURL
containerIdentifier:(NSString *)containerIdentifier storeConfiguration:(NSString *)storeConfiguration storeOptions:(NSDictionary *)storeOptions
delegate:(id<UbiquityStoreManagerDelegate>)delegate {
if (!(self = [super init]))
return nil;
// Parameters.
_delegate = delegate;
_contentName = contentName == nil? USMCloudContentName: contentName;
_model = model == nil? [NSManagedObjectModel mergedModelFromBundles:nil]: model;
if (!localStoreURL)
localStoreURL = [[[self URLForApplicationContainer]
URLByAppendingPathComponent:[self localContentName] isDirectory:NO]
URLByAppendingPathExtension:@"sqlite"];
_localStoreURL = localStoreURL;
_containerIdentifier = containerIdentifier;
_storeConfiguration = storeConfiguration;
_storeOptions = storeOptions == nil? @{ }: storeOptions;
// Private vars.
_currentIdentityToken = [[NSFileManager defaultManager] respondsToSelector:@selector(ubiquityIdentityToken)]?
[[NSFileManager defaultManager] ubiquityIdentityToken]: nil;
_cloudAvailable = (_currentIdentityToken != nil);
_migrationStrategy = &NSPersistentStoreUbiquitousContainerIdentifierKey?
UbiquityStoreMigrationStrategyIOS: UbiquityStoreMigrationStrategyCopyEntities;
_persistentStorageQueue = [NSOperationQueue new];
_persistentStorageQueue.name = [NSString stringWithFormat:@"%@PersistenceQueue", NSStringFromClass( [self class] )];
_persistentStorageQueue.maxConcurrentOperationCount = 1;
// Observe application events.
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(ubiquityStoreManagerDidDetectCorruption:)
name:UbiquityManagedStoreDidDetectCorruptionNotification
object:nil];
#if TARGET_OS_IPHONE
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(applicationDidBecomeActive:)
name:UIApplicationDidBecomeActiveNotification
object:nil];
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(userDefaultsDidChange:)
name:NSUserDefaultsDidChangeNotification
object:nil];
#else
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(applicationDidBecomeActive:)
name:NSApplicationDidBecomeActiveNotification
object:nil];
#endif
if (&NSUbiquityIdentityDidChangeNotification)
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(cloudStoreChanged:)
name:NSUbiquityIdentityDidChangeNotification
object:nil];
[self reloadStore];
return self;
}
- (void)dealloc {
// Stop listening for store changes.
[[NSNotificationCenter defaultCenter] removeObserver:self];
[self.storeFilePresenter stop];
[self.storeUUIDPresenter stop];
[self.corruptedUUIDPresenter stop];
// Unload the store.
[self enqueue:^{ [self clearStore]; } waitUntilFinished:YES];
}
#pragma mark - File Handling
- (NSString *)localContentName {
return _contentName;
}
/**
* Get the name of the cloud content for the given cloud store.
*
* For version 0 (iOS 6) this defaults to USMCloudContentName, for version 1 this is the StoreUUID.
*/
- (NSString *)cloudContentNameForStoreURL:(NSURL *)storeURL {
int cloudVersion = [self cloudVersionForStoreURL:storeURL];
return [self cloudContentNameForStoreURL:storeURL andCloudVersion:cloudVersion];
}
/**
* Get the name of the cloud content for the given cloud store.
*
* For version 0 (iOS 6) this defaults to USMCloudContentName, for version 1 this is the StoreUUID.
*/
- (NSString *)cloudContentNameForStoreURL:(NSURL *)storeURL andCloudVersion:(int)cloudVersion {
if (cloudVersion == 0)
return _contentName;
return storeURL? [[storeURL URLByDeletingPathExtension] lastPathComponent]: self.storeUUID;
}
/**
* Get a versioned version of the identifier by appending +'s to it. The version to use is determined from the storeURL.
*/
- (NSString *)cloudVersionedIdentifier:(NSString *)identifier forStoreURL:(NSURL *)storeURL {
return [self versionedIdentifier:identifier version:[self cloudVersionForStoreURL:storeURL]];
}
/**
* Get a versioned version of the identifier by appending +'s to it.
*/
- (NSString *)versionedIdentifier:(NSString *)identifier version:(int)version {
for (int v = 0; v < version; ++v)
identifier = [identifier stringByAppendingString:@"+"];
return identifier;
}
/**
* The version preferred for cloud content by the current platform when not in compatibility mode (eg. for new stores).
*
* For iOS 6, this returns 0. For iOS 7+, the version is 1.
*/
- (int)desiredCloudVersion {
if (&NSPersistentStoreUbiquitousContainerIdentifierKey)
return 1;
return 0;
}
/**
* Determine the version of the cloud store at the given URL.
*
* We find a StoreUUID file that mentions the cloud store's UUID and return its version.
* If there isn't one, this is deemed a new store and we return the desired version.
*/
- (int)cloudVersionForStoreURL:(NSURL *)storeURL {
// Determine the cloud version to use by trying the desired version for the platform and backing down
// until a StoreUUID for the version is found.
int desiredCloudVersion = [self desiredCloudVersion];
int cloudVersion = desiredCloudVersion;
NSString *forStoreUUID = [[storeURL URLByDeletingPathExtension] lastPathComponent];
for (; cloudVersion >= 0; --cloudVersion) {
NSString *storeUUIDPath = [self URLForCloudStoreUUIDForVersion:cloudVersion].path;
if ([[NSFileManager defaultManager] fileExistsAtPath:storeUUIDPath] &&
(!forStoreUUID ||
[[NSString stringWithContentsOfFile:storeUUIDPath encoding:NSUTF8StringEncoding error:nil]
isEqualToString:forStoreUUID]))
break;
}
if (cloudVersion < 0)
return desiredCloudVersion;
return cloudVersion;
}
- (NSURL *)URLForApplicationContainer {
NSURL *applicationSupportURL = [[[NSFileManager defaultManager] URLsForDirectory:NSApplicationSupportDirectory
inDomains:NSUserDomainMask] lastObject];
#if TARGET_OS_IPHONE
// On iOS, each app is in a sandbox so we don't need to app-scope this directory.
return applicationSupportURL;
#else
// The directory is shared between all apps on the system so we need to scope it for the running app.
applicationSupportURL = [applicationSupportURL URLByAppendingPathComponent:[NSRunningApplication currentApplication].bundleIdentifier isDirectory:YES];
NSError *error = nil;
if (![[NSFileManager defaultManager] createDirectoryAtURL:applicationSupportURL
withIntermediateDirectories:YES attributes:nil error:&error])
[self error:error cause:UbiquityStoreErrorCauseCreateStorePath context:applicationSupportURL.path];
return applicationSupportURL;
#endif
}
- (NSURL *)URLForCloudContainer {
return [[NSFileManager defaultManager] URLForUbiquityContainerIdentifier:self.containerIdentifier];
}
/**
* The directory where cloud store files are kept.
*
* For iOS 6, this is in a .nosync in the cloud container. For iOS 7+ in the application sandbox.
*/
- (NSURL *)URLForCloudStoreDirectory {
return [self URLForCloudStoreDirectoryForCloudVersion:[self desiredCloudVersion]];
}
/**
* The directory where cloud store files are kept.
*
* For iOS 6, this is in a .nosync in the cloud container. For iOS 7+ in the application sandbox.
*/
- (NSURL *)URLForCloudStoreDirectoryForCloudVersion:(int)version {
if (version == 0)
// iOS 6
// We put the database in the ubiquity container with a .nosync extension (must not be synced by iCloud),
// so that its presence is tied closely to whether iCloud is enabled or not on the device
// and the user can delete the store by deleting his iCloud data for the app from Settings.
return [[[self URLForCloudContainer] URLByAppendingPathComponent:USMCloudStoreDirectory isDirectory:YES]
URLByAppendingPathExtension:@"nosync"];
// On iOS7+ the store needs to be in the application container and is managed by the iCloud framework.
return [[self URLForApplicationContainer] URLByAppendingPathComponent:USMCloudStoreDirectory isDirectory:YES];
}
- (NSURL *)URLForCloudStore {
return [self URLForCloudStoreWithUUID:self.storeUUID];
}
- (NSURL *)URLForCloudStoreWithUUID:(NSString *)storeUUID {
// Our cloud store is in the cloud store databases directory and is identified by the active storeUUID.
return [[[self URLForCloudStoreDirectory] URLByAppendingPathComponent:storeUUID isDirectory:NO]
URLByAppendingPathExtension:@"sqlite"];
}
- (NSURL *)URLForCloudContentDirectory {
// The transaction logs are in the ubiquity container and are synced by iCloud.
return [[self URLForCloudContainer] URLByAppendingPathComponent:USMCloudContentDirectory isDirectory:YES];
}
- (id)URLForCloudContent {
return [self URLForCloudContentForStoreURL:nil];
}
- (id)URLForCloudContentForStoreURL:(NSURL *)storeURL {
NSString *storeUUID = storeURL? [[storeURL URLByDeletingPathExtension] lastPathComponent]: self.storeUUID;
if (&NSPersistentStoreUbiquitousContainerIdentifierKey)
return [USMCloudContentDirectory stringByAppendingPathComponent:storeUUID];
// Our cloud store's logs are in the cloud store transaction logs directory and is identified by the active storeUUID.
return [[self URLForCloudContentDirectory] URLByAppendingPathComponent:storeUUID isDirectory:YES];
}
/**
* Contrary to -URLForCloudContent, this method can return nil, in which case the location of the cloud content has not yet been established.
*/
- (id)URLForCloudContent_ThreadSafe {
NSString *storeUUID = [self storeUUID_ThreadSafe];
if (!storeUUID)
return nil;
if (&NSPersistentStoreUbiquitousContainerIdentifierKey)
return [USMCloudContentDirectory stringByAppendingPathComponent:storeUUID];
// Our cloud store's logs are in the cloud store transaction logs directory and is identified by the active storeUUID.
return [[self URLForCloudContentDirectory] URLByAppendingPathComponent:storeUUID isDirectory:YES];
}
- (NSURL *)URLForCloudStoreUUID {
// The UUID of the active cloud store is in the cloud store transaction logs directory.
return [[self URLForCloudContentDirectory]
URLByAppendingPathComponent:[self cloudVersionedIdentifier:USMCloudContentStoreUUID forStoreURL:nil]
isDirectory:NO];
}
- (NSURL *)URLForCloudStoreUUIDForVersion:(int)version {
// The UUID of the active cloud store is in the cloud store transaction logs directory.
return [[self URLForCloudContentDirectory]
URLByAppendingPathComponent:[self versionedIdentifier:USMCloudContentStoreUUID version:version]
isDirectory:NO];
}
- (NSURL *)URLForCloudCorruptedUUID {
// The UUID of the corrupted cloud store is in the cloud store transaction logs directory.
return [[self URLForCloudContentDirectory]
URLByAppendingPathComponent:[self cloudVersionedIdentifier:USMCloudContentCorruptedUUID forStoreURL:nil]
isDirectory:NO];
}
- (NSURL *)URLForCloudCorruptedUUIDForVersion:(int)version {
// The UUID of the corrupted cloud store is in the cloud store transaction logs directory.
return [[self URLForCloudContentDirectory]
URLByAppendingPathComponent:[self versionedIdentifier:USMCloudContentCorruptedUUID version:version]
isDirectory:NO];
}
- (NSURL *)URLForLocalStoreDirectory {
return [self.localStoreURL URLByDeletingLastPathComponent];
}
- (NSURL *)URLForLocalStore {
return self.localStoreURL;
}
- (NSDictionary *)enumerateCloudStores {
NSURL *cloudContentDirectory = [self URLForCloudContentDirectory];
NSError *error = nil;
NSArray *cloudContentURLs = [[NSFileManager defaultManager]
contentsOfDirectoryAtURL:cloudContentDirectory includingPropertiesForKeys:nil
options:NSDirectoryEnumerationSkipsHiddenFiles error:&error];
if (!cloudContentURLs) {
[self error:error cause:UbiquityStoreErrorCauseEnumerateStores context:cloudContentDirectory.path];
return nil;
}
int maxCloudVersion = [self desiredCloudVersion];
NSMutableDictionary *cloudStores = [NSMutableDictionary dictionary];
for (NSURL *cloudContentURL in cloudContentURLs) {
BOOL isDirectory = NO;
if (![[NSFileManager defaultManager] fileExistsAtPath:cloudContentURL.path isDirectory:&isDirectory] && !isDirectory)
continue;
NSString *storeUUID = [cloudContentURL lastPathComponent];
NSURL *storeURL = [self URLForCloudStoreWithUUID:storeUUID];
NSMutableArray *cloudStoreOptionSets = [NSMutableArray array];
NSArray *peerURLs = [[NSFileManager defaultManager] contentsOfDirectoryAtURL:cloudContentURL includingPropertiesForKeys:nil
options:NSDirectoryEnumerationSkipsHiddenFiles error:&error];
for (NSURL *peerURL in peerURLs) {
NSArray *cloudContentNameURLs = [[NSFileManager defaultManager] contentsOfDirectoryAtURL:peerURL includingPropertiesForKeys:nil
options:NSDirectoryEnumerationSkipsHiddenFiles
error:&error];
for (NSURL *cloudContentNameURL in cloudContentNameURLs) {
NSMutableDictionary *cloudStoreOptions = [self optionsForCloudStoreURL:storeURL];
NSString *cloudContentName = [cloudContentNameURL lastPathComponent];
for (int cloudVersion = maxCloudVersion; cloudVersion >= 0; --cloudVersion)
if ([cloudContentName isEqualToString:[self cloudContentNameForStoreURL:storeURL andCloudVersion:cloudVersion]]) {
cloudStoreOptions[NSPersistentStoreUbiquitousContentNameKey] = cloudContentName;
cloudStoreOptions[USMCloudVersionKey] = @(cloudVersion);
cloudStoreOptions[USMCloudCurrentKey] = @([[self storeUUID_ThreadSafe] isEqualToString:storeUUID] &&
[self cloudVersionForStoreURL:storeURL] == cloudVersion);
cloudStoreOptions[USMCloudUUIDKey] = storeUUID;
[cloudStoreOptionSets addObject:cloudStoreOptions];
break;
}
}
}
cloudStores[storeURL] = cloudStoreOptionSets;
}
return cloudStores;
}
- (void)switchToCloudStoreWithOptions:(NSDictionary *)cloudStoreOptions {
[self setStoreUUID:cloudStoreOptions[USMCloudUUIDKey] withCloudVersion:[cloudStoreOptions[USMCloudVersionKey] intValue]];
if (self.cloudEnabled)
[self reloadStore];
}
#pragma mark - Utilities
- (void)log:(NSString *)format, ... NS_FORMAT_FUNCTION(1, 2) {
va_list argList;
va_start(argList, format);
NSString *message = [[NSString alloc] initWithFormat:format arguments:argList];
va_end(argList);
if ([self.delegate respondsToSelector:@selector(ubiquityStoreManager:log:)])
[self.delegate ubiquityStoreManager:self log:message];
else
MyLog( @"UbiquityStoreManager: %@", message );
}
- (void)logError:(NSString *)error cause:(UbiquityStoreErrorCause)cause context:(id)context {
[self error:[NSError errorWithDomain:NSCocoaErrorDomain code:0 userInfo:@{ NSLocalizedFailureReasonErrorKey : error }]
cause:cause context:context];
}
- (void)error:(NSError *)error cause:(UbiquityStoreErrorCause)cause context:(id)context {
if ([self.delegate respondsToSelector:@selector(ubiquityStoreManager:didEncounterError:cause:context:)])
[self.delegate ubiquityStoreManager:self didEncounterError:error cause:cause context:context];
else {
[self log:@"Error (cause:%@): %@", NSStringFromUSMCause( cause ), error];
if (context)
[self log:@" - Context : %@", context];
NSError *underlyingError = [error userInfo][NSUnderlyingErrorKey];
if (underlyingError)
[self log:@" - Underlying: %@", underlyingError];
NSArray *detailedErrors = [error userInfo][NSDetailedErrorsKey];
for (NSError *detailedError in detailedErrors)
[self log:@" - Detail : %@", detailedError];
}
}
- (void)assertQueued {
NSAssert([NSOperationQueue currentQueue] == self.persistentStorageQueue, @"This call may only be invoked from the persistence queue.");
}
/**
* @return YES if we are currently on the persistence queue. NO if we aren't and the enqueueBlock has been submitted to it.
*/
- (BOOL)ensureQueued:(void (^)())enqueueBlock {
if ([NSOperationQueue currentQueue] == self.persistentStorageQueue)
return YES;
[self enqueue:enqueueBlock];
return NO;
}
- (void)enqueue:(void (^)())enqueueBlock {
[self enqueue:enqueueBlock waitUntilFinished:NO];
}
- (void)enqueue:(void (^)())enqueueBlock waitUntilFinished:(BOOL)wait {
[self enqueue:enqueueBlock waitUntilFinished:NO lock:YES];
}
- (void)enqueue:(void (^)())enqueueBlock waitUntilFinished:(BOOL)wait lock:(BOOL)lock {
[self.persistentStorageQueue addOperations:@[
[NSBlockOperation blockOperationWithBlock:^{
@try {
if (lock)
[self.persistentStoreCoordinator lock];
enqueueBlock();
}
@catch (NSException *exception) {
[self logError:[(id<NSObject>)exception description]
cause:UbiquityStoreErrorCauseOpenActiveStore context:exception];
}
@finally {
if (lock)
[self.persistentStoreCoordinator unlock];
}
}]
] waitUntilFinished:wait];
}
#pragma mark - Store Management
- (NSPersistentStoreCoordinator *)persistentStoreCoordinator {
[self assertQueued];
if (!_persistentStoreCoordinator) {
_persistentStoreCoordinator = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:self.model];
if (&NSPersistentStoreDidImportUbiquitousContentChangesNotification)
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(didImportChanges:)
name:NSPersistentStoreDidImportUbiquitousContentChangesNotification
object:_persistentStoreCoordinator];
if (&NSPersistentStoreCoordinatorStoresWillChangeNotification)
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(storesWillChange:)
name:NSPersistentStoreCoordinatorStoresWillChangeNotification
object:_persistentStoreCoordinator];
if (&NSPersistentStoreCoordinatorStoresDidChangeNotification)
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(storesDidChange:)
name:NSPersistentStoreCoordinatorStoresDidChangeNotification
object:_persistentStoreCoordinator];
}
return _persistentStoreCoordinator;
}
- (void)resetPersistentStoreCoordinator {
[self assertQueued];
if (_persistentStoreCoordinator) {
[_persistentStoreCoordinator unlock];
[[NSNotificationCenter defaultCenter] removeObserver:self name:nil object:_persistentStoreCoordinator];
_persistentStoreCoordinator = nil;
}
[self.persistentStoreCoordinator lock];
}
- (void)clearStore {
[self log:@"Clearing stores..."];
[self assertQueued];
// Stop listening for store changes.
[self.storeFilePresenter stop];
[self.storeUUIDPresenter stop];
[self.corruptedUUIDPresenter stop];
// Let the application clean up its MOCs.
[self.persistentStoreCoordinator unlock];
[self fireBeginLoadingLogReason:@"Will clear stores"];
// Remove the store from the coordinator.
NSError *error = nil;
self.activeCloudStoreUUID = nil;
for (NSPersistentStore *store in self.persistentStoreCoordinator.persistentStores)
if (![self.persistentStoreCoordinator removePersistentStore:store error:&error])
[self error:error cause:UbiquityStoreErrorCauseClearStore context:store];
// If we failed to remove all the stores, throw away the PSC and create a new one.
if ([[self.persistentStoreCoordinator persistentStores] count])
[self resetPersistentStoreCoordinator];
else
[self.persistentStoreCoordinator lock];
// Set up the file presenters.
self.storeUUIDPresenter = [[USMStoreUUIDPresenter alloc] initWithUSM:self];
self.corruptedUUIDPresenter = [[USMCorruptedUUIDPresenter alloc] initWithUSM:self];
self.storeFilePresenter = [[USMLocalStoreFilePresenter alloc] initWithUSM:self];
if (self.cloudEnabled) {
[self.storeUUIDPresenter start];
[self.corruptedUUIDPresenter start];
}
else {
[self.storeFilePresenter start];
}
}
- (void)reloadStore {
if (![self ensureQueued:^{ [self reloadStore]; }])
return;
[self log:@"%@ store...", [[self.persistentStoreCoordinator persistentStores] count]? @"Reloading": @"Loading"];
// If user is not logged into iCloud, don't try to cloud cloud store: It will fail and not due to corruption.
BOOL cloudEnabled = self.cloudEnabled;
if (cloudEnabled && ![[NSFileManager defaultManager] ubiquityIdentityToken]) {
[self log:@"Cannot load cloud store: User is not logged into iCloud. Falling back to local store."];
cloudEnabled = NO;
if (!self.cloudWasEnabled)
// Cloud was disabled and can't enable it, we don't need to reload: the local store is already active.
return;
}
// Load the requested store. If the cloud store fails to load, mark it corrupt so we can try to recover it.
if (cloudEnabled) {
if (![self tryLoadCloudStore]) {
// Failed to load regardless of recovery attempt. Mark store as corrupt.
[self log:@"Failed to load cloud store. Marking cloud store as corrupt. Store will be unavailable."];
[self markCloudStoreCorrupted];
}
}
else
[self tryLoadLocalStore];
}
- (BOOL)tryLoadCloudStore {
[self log:@"Will load cloud store."];
[self assertQueued];
// Check if the user is logged into iCloud on the device.
if (![[NSFileManager defaultManager] ubiquityIdentityToken]) {
[self log:@"Could not load cloud store: User is not logged into iCloud."];
return NO;
}
// Clear the active persistence store and mark cloud as enabled.
self.cloudWasEnabled = YES;
[self clearStore];
self.activeCloudStoreUUID = nil;
// Begin loading the cloud store 'atomically'.
id context = nil;
UbiquityStoreErrorCause cause = UbiquityStoreErrorCauseNoError;
@try {
NSURL *cloudStoreURL = [self URLForCloudStore];
[self log:@"Loading cloud store: %@, v%d (%@).", [self storeUUIDForLog], [self cloudVersionForStoreURL:cloudStoreURL],
_tentativeStoreUUID? @"tentative": @"definite"];
// Check if we need to seed the store by migrating another store into it.
UbiquityStoreMigrationStrategy migrationStrategy = self.migrationStrategy;
[self log:@"[DEBUG] migrationStoreURL: %@", self.migrationStoreURL];
NSURL *migrationStoreURL = self.migrationStoreURL? self.migrationStoreURL: [self localStoreURL];
NSMutableDictionary *migrationStoreOptions = [self optionsForMigrationStoreURL:migrationStoreURL];
[self log:@"[DEBUG] migrationStoreOptions: %@", migrationStoreOptions];
[self log:@"[DEBUG] cloudSafeForSeeding: %d", [self cloudSafeForSeeding]];
if (migrationStrategy == UbiquityStoreMigrationStrategyNone ||
!migrationStoreOptions || ![self cloudSafeForSeeding] ||
// We want to migrate from migrationStoreURL, check with application.
([self.delegate respondsToSelector:@selector(ubiquityStoreManager:shouldMigrateFromStoreURL:toStoreURL:isCloud:)] &&
![self.delegate ubiquityStoreManager:self
shouldMigrateFromStoreURL:migrationStoreURL toStoreURL:cloudStoreURL
isCloud:YES])) {
[self log:@"[DEBUG] Will NOT migrate to cloud store from: %@ (strategy: %d).", [migrationStoreURL lastPathComponent],
migrationStrategy];
migrationStrategy = UbiquityStoreMigrationStrategyNone;
migrationStoreURL = nil;
}
else
[self log:@"Will migrate to cloud store from: %@ (strategy: %d).", [migrationStoreURL lastPathComponent],
migrationStrategy];
// Load the cloud store.
NSMutableDictionary *cloudStoreOptions = [self optionsForCloudStoreURL:cloudStoreURL];
if (self.attemptCloudRecovery) {
if (&NSPersistentStoreRebuildFromUbiquitousContentOption)
// iOS 7+
cloudStoreOptions[NSPersistentStoreRebuildFromUbiquitousContentOption] = @YES;
else
// iOS 6
[self deleteCloudStoreLocalOnly:YES];
}
[self loadStoreAtURL:cloudStoreURL withOptions:cloudStoreOptions
migratingStoreAtURL:migrationStoreURL withOptions:migrationStoreOptions
usingStrategy:migrationStrategy cause:&cause context:&context];
}
@catch (id exception) {
[self logError:[(id<NSObject>)exception description]
cause:cause = UbiquityStoreErrorCauseOpenActiveStore context:context = exception];
}
@finally {
if (cause == UbiquityStoreErrorCauseNoError) {
// Store loaded successfully.
[self confirmTentativeStoreUUID];
self.activeCloudStoreUUID = [self storeUUID];
self.attemptCloudRecovery = NO;
self.migrationStoreURL = nil;
[self log:@"Successfully loaded cloud store."];
}
else {
// An error occurred in the @try block.
[self logError:@"Failed to load cloud store." cause:cause context:context];
[self unsetTentativeStoreUUID];
[self clearStore];
// If we haven't attempted recovery yet (ie. delete the cloud store file), try that first.
if (!self.attemptCloudRecovery) {
[self log:@"Attempting recovery by rebuilding from cloud content."];
self.attemptCloudRecovery = YES;
return [self tryLoadCloudStore];
}
self.attemptCloudRecovery = NO;
}
}
// Notify the application.
[self fireFinishedLoadingLogReason:@"Finished loading cloud store" cause:cause context:context];
return cause == UbiquityStoreErrorCauseNoError;
}
- (BOOL)tryLoadLocalStore {
[self log:@"Will load local store."];
[self assertQueued];
// Clear the active persistence store and mark cloud as disabled.
self.cloudWasEnabled = NO;
[self clearStore];
id context = nil;
UbiquityStoreErrorCause cause = UbiquityStoreErrorCauseNoError;
@try {
NSURL *localStoreURL = [self URLForLocalStore];
NSURL *migrationStoreURL = self.migrationStoreURL;
UbiquityStoreMigrationStrategy migrationStrategy = self.migrationStrategy;
NSMutableDictionary *migrationStoreOptions = [self optionsForMigrationStoreURL:migrationStoreURL];
if (migrationStrategy == UbiquityStoreMigrationStrategyNone ||
!migrationStoreOptions ||
// We want to migrate from migrationStoreURL, check with application.
([self.delegate respondsToSelector:@selector(ubiquityStoreManager:shouldMigrateFromStoreURL:toStoreURL:isCloud:)] &&
![self.delegate ubiquityStoreManager:self
shouldMigrateFromStoreURL:migrationStoreURL toStoreURL:localStoreURL
isCloud:NO]) ||
// Migration OK'ed by application, make sure destination store doesn't exist.
[[NSFileManager defaultManager] fileExistsAtPath:localStoreURL.path])
migrationStrategy = UbiquityStoreMigrationStrategyNone;
else
[self log:@"Will migrate to local store from: %@ (strategy: %d).", [migrationStoreURL lastPathComponent], migrationStrategy];
// Load the local store.
[self loadStoreAtURL:localStoreURL withOptions:[self optionsForLocalStore]
migratingStoreAtURL:migrationStoreURL withOptions:migrationStoreOptions
usingStrategy:migrationStrategy cause:&cause context:&context];
}
@catch (id exception) {
[self logError:[(id<NSObject>)exception description]
cause:cause = UbiquityStoreErrorCauseOpenActiveStore context:context = exception];
}
@finally {
if (cause == UbiquityStoreErrorCauseNoError) {
// Store loaded successfully.
self.migrationStoreURL = nil;
[self log:@"Successfully loaded local store."];
}
else {
// An error occurred in the @try block.
[self logError:@"Failed to load local store." cause:cause context:context];
[self clearStore];
}
// Notify the application.
[self fireFinishedLoadingLogReason:@"Finished loading local store" cause:cause context:context];
}
return cause == UbiquityStoreErrorCauseNoError;
}
- (void)fireBeginLoadingLogReason:(NSString *)reason {
if ([NSOperationQueue currentQueue] != self.persistentStorageQueue) {
[self enqueue:^{ [self fireBeginLoadingLogReason:reason]; } waitUntilFinished:YES lock:NO];
return;
}
[self log:@"%@. Notifying application to reset its UI.", reason];
if ([self.delegate respondsToSelector:@selector(ubiquityStoreManager:willLoadStoreIsCloud:)])
[self.delegate ubiquityStoreManager:self willLoadStoreIsCloud:self.cloudEnabled];
[[NSNotificationCenter defaultCenter] postNotificationName:USMStoreWillChangeNotification object:self userInfo:nil];
// Invalidate any previous finished notifications.
[self.finishedLoadingOperation cancel];
}
- (void)fireFinishedLoadingLogReason:(NSString *)reason cause:(UbiquityStoreErrorCause)cause context:(id)context {
[self.finishedLoadingOperation cancel];
self.finishedLoadingOperation = [NSBlockOperation blockOperationWithBlock:^{
[self log:@"%@ (%@). Notifying application to refresh its UI.", reason, NSStringFromUSMCause( cause )];
if (cause == UbiquityStoreErrorCauseNoError && self.persistentStoreCoordinator) {
if ([self.delegate respondsToSelector:@selector(ubiquityStoreManager:didLoadStoreForCoordinator:isCloud:)])
[self.delegate ubiquityStoreManager:self didLoadStoreForCoordinator:self.persistentStoreCoordinator
isCloud:self.cloudEnabled];
[[NSNotificationCenter defaultCenter] postNotificationName:USMStoreDidChangeNotification object:self userInfo:nil];
// A cloud store that is ubiquitized or has just completed the initial import is deemed healthy if it survives for 30s.
// The delay is to allow importing pending transaction logs.
// A healthy store can be used to bump the cloud version or resolve cloud corruption.
if (self.cloudEnabled &&
((&NSPersistentStoreUbiquitousTransitionTypeKey &&
[context isKindOfClass:[NSNotification class]] &&
[((NSNotification *)context).userInfo[NSPersistentStoreUbiquitousTransitionTypeKey] unsignedIntegerValue] ==
NSPersistentStoreUbiquitousTransitionTypeInitialImportCompleted) ||
([((NSPersistentStore *)[self.persistentStoreCoordinator.persistentStores lastObject])
.metadata[@"com.apple.coredata.ubiquity.ubiquitized"] boolValue])))
dispatch_after( dispatch_time( DISPATCH_TIME_NOW, NSEC_PER_SEC * 30 ),
dispatch_get_global_queue( DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0 ), ^{
[self enqueue:^{
if ([self cloudVersionForStoreURL:nil] != [self desiredCloudVersion]) {
[self log:@"Cloud store is healthy but version is below desired. Will rebuild to upgrade."];
[self rebuildCloudContentFromCloudStoreOrLocalStore:NO];
}
else if (self.activeCloudStoreUUID && ![self.localCloudStoreCorruptedUUID isEqualToString:self.storeUUID])
[self handleCloudContentCorruption];
}];
} );
}
else {
if ([self.delegate respondsToSelector:@selector(ubiquityStoreManager:failedLoadingStoreWithCause:context:wasCloud:)])
[self.delegate ubiquityStoreManager:self failedLoadingStoreWithCause:cause context:context wasCloud:self.cloudEnabled];
}
}];
[self.persistentStorageQueue addOperation:self.finishedLoadingOperation];
}
- (NSMutableDictionary *)optionsForLocalStore {
NSMutableDictionary *localStoreOptions = [@{
NSMigratePersistentStoresAutomaticallyOption : @YES,
NSInferMappingModelAutomaticallyOption : @YES
} mutableCopy];
[localStoreOptions addEntriesFromDictionary:self.storeOptions];
return localStoreOptions;
}
- (NSMutableDictionary *)optionsForCloudStoreURL:(NSURL *)cloudStoreURL {
NSString *cloudContentName = [self cloudContentNameForStoreURL:cloudStoreURL];
NSURL *cloudStoreContentURL = [self URLForCloudContentForStoreURL:cloudStoreURL];
NSMutableDictionary *cloudStoreOptions = [@{
NSPersistentStoreUbiquitousContentNameKey : cloudContentName,
NSPersistentStoreUbiquitousContentURLKey : cloudStoreContentURL,
NSMigratePersistentStoresAutomaticallyOption : @YES,
NSInferMappingModelAutomaticallyOption : @YES
} mutableCopy];
if (&NSPersistentStoreUbiquitousContainerIdentifierKey) {
// iOS 7+
// Cloud store loading options.
if (self.containerIdentifier)
cloudStoreOptions[NSPersistentStoreUbiquitousContainerIdentifierKey] = self.containerIdentifier;
}
else {
// iOS 6
// Clean up the cloud store if the cloud content got deleted.
BOOL storeExists = [[NSFileManager defaultManager] fileExistsAtPath:cloudStoreURL.path];
BOOL storeContentExists = [[NSFileManager defaultManager] startDownloadingUbiquitousItemAtURL:cloudStoreContentURL error:nil];
if (storeExists && !storeContentExists) {
// We have a cloud store but no cloud content. The cloud content was deleted:
// The existing store cannot sync anymore and needs to be recreated.
[self log:@"Deleting cloud store: it has no cloud content."];
[[NSFileManager defaultManager] removeItemAtURL:cloudStoreURL error:nil];
}
}
[cloudStoreOptions addEntriesFromDictionary:self.storeOptions];
return cloudStoreOptions;
}
- (NSMutableDictionary *)optionsForMigrationStoreURL:(NSURL *)migrationStoreURL {
if (!migrationStoreURL)
return nil;