-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathHICloudManager.m
303 lines (258 loc) · 13.9 KB
/
HICloudManager.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
//
// HICloudManager.m
// Hab It!
//
// Created by orkenstein on 10.03.14.
// Copyright (c) 2014 savefon.mobi. All rights reserved.
//
#import "HICloudManager.h"
#import "HISettingsManager.h"
#import <MMProgressHUD.h>
NSString *const HIICloudDataImportedNotification = @"HIICloudDataImportedNotification";
NSString *const HICoreDataStackInitNotification = @"HICoreDataStackInitNotification";
static NSString *const kICloudStoreName = @"iCloudStore.sqlite";
static NSString *const kICloudContentNameKey = @"savefonmobiHabIt";
@interface HICloudManager ()
@property(nonatomic, assign) BOOL coreDataInitialised;
@property(nonatomic, copy) NSData *currentICloudToken;
@property(nonatomic, copy) NSURL *lastICloudStoreURL;
@end
@interface NSPersistentStoreCoordinator ()
+ (NSDictionary *)MR_autoMigrationOptions;
- (void)MR_createPathToStoreFileIfNeccessary:(NSURL *)urlForStore;
@end
@implementation HICloudManager
SHARED_INSTANCE_GCD_USING_BLOCK(^{
HICloudManager *manager = [[HICloudManager alloc] init];
[manager registerNotifications];
return manager;
})
#pragma mark - Notifications
- (void)registerNotifications {
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(storeDidImportNotifications:)
name:NSPersistentStoreDidImportUbiquitousContentChangesNotification
object:nil];
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(storeDidChangeNotifications:)
name:NSPersistentStoreCoordinatorStoresDidChangeNotification
object:nil];
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(storeWillChangeNotifications:)
name:NSPersistentStoreCoordinatorStoresWillChangeNotification
object:nil];
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(storeWillRemoveChangeNotifications:)
name:NSPersistentStoreCoordinatorWillRemoveStoreNotification
object:nil];
}
- (void)dealloc {
[[NSNotificationCenter defaultCenter] removeObserver:self];
}
- (void)storeDidImportNotifications:(NSNotification *)notification {
}
- (void)storeDidChangeNotifications:(NSNotification *)notification {
NSPersistentStoreUbiquitousTransitionType type =
[notification.userInfo[NSPersistentStoreUbiquitousTransitionTypeKey] integerValue];
BOOL importCompleted = (type == NSPersistentStoreUbiquitousTransitionTypeInitialImportCompleted);
if (importCompleted == YES) {
[__settings setDefaults:@(YES) forKey:HIICloudImportedKey];
[MMProgressHUD dismissWithSuccess:NSLocalizedString(@"Success!", nil)];
[[NSNotificationCenter defaultCenter] postNotificationName:HIICloudDataImportedNotification object:self];
}
}
- (void)storeWillChangeNotifications:(NSNotification *)notification {
}
- (void)storeWillRemoveChangeNotifications:(NSNotification *)notification {
}
- (BOOL)iCloudAvailable {
id currentiCloudToken = [[NSFileManager defaultManager] ubiquityIdentityToken];
return currentiCloudToken != nil;
}
#pragma mark - Core Data
- (void)setupCoreDataICloudEnable:(BOOL)iCloudEnabled withCompletion:(void (^)(void))completion {
BOOL currentiCloudSetting = ([[__settings defaultsForKey:HIICloudSettingKey] integerValue] == HIICloudSettingEnabled);
// Skip the same setting. No need to bother Core Data...
if (currentiCloudSetting == iCloudEnabled && self.coreDataInitialised == YES) {
if (completion != nil) {
completion();
return;
}
}
// We going to change iCloud setting, so migrate, if stack alredy exists.
BOOL shouldMigrateStore = self.coreDataInitialised;
if (iCloudEnabled == YES && [self iCloudAvailable] == YES) {
id currentiCloudToken = [[NSFileManager defaultManager] ubiquityIdentityToken];
self.currentICloudToken = currentiCloudToken;
[__settings setDefaults:currentiCloudToken forKey:HIICloudLastTokenKey];
if ([[__settings defaultsForKey:HIICloudImportedKey] boolValue] == NO && self.lastICloudStoreURL == nil) {
[MMProgressHUD showWithTitle:NSLocalizedString(@"iCloud_Importing_HUD_title", nil)
status:NSLocalizedString(@"iCloud_Importing_HUD_status", nil)];
[MMProgressHUD dismissAfterDelay:120];
}
if (shouldMigrateStore == YES) {
[self migrateLocalToFallbackStore];
// Ensure
[MagicalRecord cleanUp];
// remove existing icloud store
// NSError *error = nil;
// NSURL *fallbackURL = [NSPersistentStore MR_urlForStoreName:kICloudStoreName];
// NSURL *iCloudURL = [NSPersistentStore MR_cloudURLForUbiqutiousContainer:nil];
// NSDictionary *iCloudOptions =
// [NSDictionary dictionaryWithObjectsAndKeys:kICloudContentNameKey, NSPersistentStoreUbiquitousContentNameKey,
// iCloudURL, NSPersistentStoreUbiquitousContentURLKey, nil];
// BOOL result = [NSPersistentStoreCoordinator removeUbiquitousContentAndPersistentStoreAtURL:self.lastICloudStoreURL
// options:iCloudOptions
// error:&error];
// NSLog(@"Icloud store was removed with result: %@\r Error: %@", result ? @"YES" : @"NO", error);
}
// Setup iCloud stack
[MagicalRecord setupCoreDataStackWithiCloudContainer:nil
contentNameKey:kICloudContentNameKey
localStoreNamed:kICloudStoreName
cloudStorePathComponent:nil
completion:^{
// Notify
self.coreDataInitialised = YES;
[[NSNotificationCenter defaultCenter]
postNotificationName:HICoreDataStackInitNotification
object:self];
self.lastICloudStoreURL = [[NSPersistentStore MR_defaultPersistentStore] URL];
if (completion != nil) {
completion();
}
}];
} else {
if (shouldMigrateStore == YES) {
[self migrateFallbackToLocalStore];
// Ensure
[MagicalRecord cleanUp];
}
// Setup usual stack
[MagicalRecord setupAutoMigratingCoreDataStack];
// Notify
self.coreDataInitialised = YES;
[[NSNotificationCenter defaultCenter] postNotificationName:HICoreDataStackInitNotification object:self];
if (completion != nil) {
completion();
}
}
}
- (void)migrateLocalToFallbackStore {
NSPersistentStore *currentLocalStore = [NSPersistentStore MR_defaultPersistentStore];
NSURL *fallbackURL = [NSPersistentStore MR_urlForStoreName:kICloudStoreName];
NSURL *iCloudURL = [NSPersistentStore MR_cloudURLForUbiqutiousContainer:nil];
NSDictionary *iCloudOptions =
[NSDictionary dictionaryWithObjectsAndKeys:kICloudContentNameKey, NSPersistentStoreUbiquitousContentNameKey,
iCloudURL, NSPersistentStoreUbiquitousContentURLKey, nil];
NSLog(@"Migrate local store:\r\r%@\r\rTo URL:\r%@\r", currentLocalStore, fallbackURL);
// do the stuff
[self migrateStore:currentLocalStore toUrl:self.lastICloudStoreURL withOptions:iCloudOptions removeExisting:YES];
}
- (void)migrateFallbackToLocalStore {
NSPersistentStore *currentFallbackStore = [NSPersistentStore MR_defaultPersistentStore];
NSURL *localURL = [NSPersistentStore MR_urlForStoreName:[MagicalRecord defaultStoreName]];
NSMutableDictionary *migrateStoreOptions =
[NSMutableDictionary dictionaryWithObjectsAndKeys:@YES, NSPersistentStoreRemoveUbiquitousMetadataOption,
@YES, NSMigratePersistentStoresAutomaticallyOption,
/*@YES, NSInferMappingModelAutomaticallyOption,*/ nil];
NSLog(@"Migrate fallback store:\r\r%@\r\rTo URL:\r%@\r", currentFallbackStore, localURL);
[self migrateStore:currentFallbackStore toUrl:localURL withOptions:migrateStoreOptions removeExisting:YES];
}
- (void)migrateStore:(NSPersistentStore *)store
toUrl:(NSURL *)migrateURL
withOptions:(NSDictionary *)options
removeExisting:(BOOL)removeExisting {
if (store == nil || migrateURL == nil) {
return;
}
NSFileCoordinator *coordinator = [[NSFileCoordinator alloc] init];
// Perform the stuff coordinated
[coordinator coordinateWritingItemAtURL:migrateURL options:NSFileCoordinatorWritingForReplacing error:nil byAccessor:^(NSURL *newURL) {
NSLog(@"Content of migration folder:\r%@",
[[NSFileManager defaultManager] contentsOfDirectoryAtPath:[[newURL URLByDeletingLastPathComponent] path]
error:nil]);
// remove previous file
if ([[NSFileManager defaultManager] fileExistsAtPath:newURL.path] == YES && removeExisting == YES) {
[[NSFileManager defaultManager] removeItemAtURL:newURL error:nil];
NSLog(@"Content of migration folder (item was removed):\r%@",
[[NSFileManager defaultManager] contentsOfDirectoryAtPath:[[newURL URLByDeletingLastPathComponent] path]
error:nil]);
}
[[NSPersistentStoreCoordinator MR_defaultStoreCoordinator] MR_createPathToStoreFileIfNeccessary:newURL];
NSError *error = nil;
[[NSPersistentStoreCoordinator MR_defaultStoreCoordinator] lock];
NSPersistentStore *newStore =
[[NSPersistentStoreCoordinator MR_defaultStoreCoordinator] migratePersistentStore:store
toURL:newURL
options:options
withType:NSSQLiteStoreType
error:&error];
[[NSPersistentStoreCoordinator MR_defaultStoreCoordinator] unlock];
NSAssert(newStore != nil, @"Migration failed:\r%@", error);
NSLog(@"Content of migration folder\r%@",
[[NSFileManager defaultManager] contentsOfDirectoryAtPath:[[newURL URLByDeletingLastPathComponent] path]
error:nil]);
}];
}
- (void)grantICloudAccess:(BOOL)dialogOnlyIfNeeded withCompletion:(void (^)(BOOL))completion {
HIICloudSetting iCloudSetting = [[__settings defaultsForKey:HIICloudSettingKey] integerValue];
if (iCloudSetting == HIICloudSettingUnknown || dialogOnlyIfNeeded == NO) {
[self showICloudDialogWithCompletion:^(HIICloudSetting blockiCloudSetting) {
// Setup Core Data after dialog
BOOL enableICloud = (blockiCloudSetting == HIICloudSettingEnabled);
[__cloud setupCoreDataICloudEnable:enableICloud
withCompletion:^{
[__settings setDefaults:@(blockiCloudSetting) forKey:HIICloudSettingKey];
if (completion != nil) {
completion(enableICloud);
}
}];
}];
} else {
BOOL enableICloud = (iCloudSetting == HIICloudSettingEnabled);
[__cloud setupCoreDataICloudEnable:enableICloud
withCompletion:^{
if (completion != nil) {
completion(enableICloud);
}
}];
}
}
- (void)showICloudDialogWithCompletion:(void (^)(HIICloudSetting iCloudSetting))completion {
UIAlertView *alert = nil;
BOOL iCloudAvailable = [self iCloudAvailable];
if (iCloudAvailable == YES) {
alert = [UIAlertView alertWithTitle:NSLocalizedString(@"iCloud_alert_title", nil)
message:NSLocalizedString(@"iCloud_enable_alert_message", nil)];
[alert addButtonWithTitle:NSLocalizedString(@"iCloud_enable_alert_use_option", nil)
handler:^(UIAlertView *alert) {
if (completion != nil) {
completion(HIICloudSettingEnabled);
}
}];
[alert addButtonWithTitle:NSLocalizedString(@"iCloud_enable_alert_do_not_use_option", nil)
handler:^(UIAlertView *alert) {
if (completion != nil) {
completion(HIICloudSettingDisabled);
}
}];
} else {
alert = [UIAlertView alertWithTitle:NSLocalizedString(@"iCloud_alert_title", nil)
message:NSLocalizedString(@"iCloud_unavailable_alert_message", nil)];
[alert addButtonWithTitle:NSLocalizedString(@"OK", nil)
handler:^(UIAlertView *alert) {
if (completion != nil) {
completion(HIICloudSettingUnknown);
}
}];
[alert addButtonWithTitle:NSLocalizedString(@"iCloud_enable_alert_do_not_use_option", nil)
handler:^(UIAlertView *alert) {
if (completion != nil) {
completion(HIICloudSettingDisabled);
}
}];
}
[alert show];
}
@end