-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathPodsterManagedDocument.m
236 lines (211 loc) · 8.39 KB
/
PodsterManagedDocument.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
//
// PodsterManagedDocument.m
// podster
//
// Created by Vanterpool, Stephen on 3/13/12.
// Copyright (c) 2012 __MyCompanyName__. All rights reserved.
//
#import "BlockAlertView.h"
#import "PodsterManagedDocument.h"
#import "NSManagedObject+MagicalRecord.h"
#define SharedFileName @"PodsterData"
#define PrivateName @"net.vanterpool.podster.data"
#import "CloudHelper.h"
@implementation PodsterManagedDocument
{
NSMutableArray *readyCallbacks;
}
+ (BOOL) isICloudEnabled;
{
NSURL *cloudURL = [NSPersistentStore MR_cloudURLForUbiqutiousContainer:nil];
return cloudURL != nil;
}
+ (PodsterManagedDocument *)sharedInstance
{
static PodsterManagedDocument *doc = nil;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
NSURL *docURL = [CloudHelper localFileURL:SharedFileName];
doc = [[PodsterManagedDocument alloc] initWithFileURL:docURL];
[doc loadDocument:^{
[doc executeReadyCallbacks];
}];
});
return doc;
}
+(NSManagedObjectContext *)defaultContext
{
NSAssert([self sharedInstance].documentState == UIDocumentStateNormal, @"This should only be called after the document is opened");
return [self sharedInstance].managedObjectContext;
}
+ (NSURL *)applicationDocumentsDirectory
{
NSString *path = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
NSURL *url = [NSURL fileURLWithPath:path];
return url;
}
-(id)initWithFileURL:(NSURL *)url
{
self = [super initWithFileURL:url];
if (self) {
readyCallbacks = [NSMutableArray array];
}
return self;
}
- (void)executeReadyCallbacks
{
LOG_GENERAL(2, @"Document Ready. Executing Callback");
dispatch_async(dispatch_get_main_queue(), ^{
[readyCallbacks enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
ContextBlock callback = obj;
callback();
}];
[readyCallbacks removeAllObjects];
});
// [[NSNotificationCenter defaultCenter]addObserver:self
// selector:@selector(documentContentsDidUpdate:)
// name:NSPersistentStoreDidImportUbiquitousContentChangesNotification
// object:nil];
//
}
//- (void) documentContentsDidUpdate: (NSNotification *) notification
//{
// NSDictionary* userInfo = [notification userInfo];
// [self.managedObjectContext performBlock:^{
// [self mergeiCloudChanges:userInfo forContext:self.managedObjectContext];}];
//}
#pragma mark Courtesy of Apple. Thank you Apple
// Merge the iCloud changes into the managed context
//- (void)mergeiCloudChanges: (NSDictionary*)userInfo
// forContext: (NSManagedObjectContext*)managedObjectContext
//{
// @autoreleasepool
//
// {
// NSMutableDictionary *localUserInfo =
// [NSMutableDictionary dictionary];
//
// // Handle the invalidations
// NSSet* allInvalidations =
// [userInfo objectForKey:NSInvalidatedAllObjectsKey];
// NSString* materializeKeys[] = { NSDeletedObjectsKey,
// NSInsertedObjectsKey };
// if (nil == allInvalidations)
// {
// int c = (sizeof(materializeKeys) / sizeof(NSString*));
// for (int i = 0; i < c; i++)
// {
// NSSet* set = [userInfo objectForKey:materializeKeys[i]];
// if ([set count] > 0)
// {
// NSMutableSet* objectSet = [NSMutableSet set];
// for (NSManagedObjectID* moid in set)
// [objectSet addObject:[managedObjectContext
// objectWithID:moid]];
// [localUserInfo setObject:objectSet
// forKey:materializeKeys[i]];
// }
// }
// // Handle the updated and refreshed Items
// NSString* noMaterializeKeys[] = { NSUpdatedObjectsKey,
// NSRefreshedObjectsKey, NSInvalidatedObjectsKey };
// c = (sizeof(noMaterializeKeys) / sizeof(NSString*));
//
// for (int i = 0; i < 2; i++)
// {
// NSSet* set = [userInfo objectForKey:noMaterializeKeys[i]];
// if ([set count] > 0)
// {
// NSMutableSet* objectSet = [NSMutableSet set];
// for (NSManagedObjectID* moid in set)
// {
// NSManagedObject* realObj =
// [managedObjectContext
// objectRegisteredForID:moid];
// if (realObj)
// [objectSet addObject:realObj];
// }
// [localUserInfo setObject:objectSet
// forKey:noMaterializeKeys[i]];
// }
// }
// // Fake a save to merge the changes
// NSNotification *fakeSave = [NSNotification
// notificationWithName:
// NSManagedObjectContextDidSaveNotification
// object:self userInfo:localUserInfo];
// [managedObjectContext
// mergeChangesFromContextDidSaveNotification:fakeSave];
// }
// else
// [localUserInfo setObject:allInvalidations
// forKey:NSInvalidatedAllObjectsKey];
//
// [managedObjectContext processPendingChanges];
// [self performSelectorOnMainThread:@selector(performFetch)
// withObject:nil waitUntilDone:NO];
// }
//}
- (void)performWhenReady:(ContextBlock)ready
{
if(self.documentState == UIDocumentStateNormal) {
ready();
} else {
[readyCallbacks addObject:[ready copy]];
}
}
- (void)loadDocument:(void (^)())opened
{
NSURL *docURL = [CloudHelper localFileURL:SharedFileName];
// Set the persistent store options to point to the cloud
NSMutableDictionary *options = [NSMutableDictionary dictionaryWithObjectsAndKeys:
[NSNumber numberWithBool:YES],
NSMigratePersistentStoresAutomaticallyOption,
[NSNumber numberWithBool:YES],
NSInferMappingModelAutomaticallyOption,
nil];
// Icloud Initialization
// NSURL *cloudURL = [CloudHelper ubiquityDataFileURL:PrivateName];
// if (cloudURL) {
// [options setValue:PrivateName forKey:NSPersistentStoreUbiquitousContentNameKey ];
// [options setValue:cloudURL forKey:NSPersistentStoreUbiquitousContentURLKey];
// }
self.persistentStoreOptions = options;
if ([[NSFileManager defaultManager] fileExistsAtPath:[docURL path]]) {
[self openWithCompletionHandler:^(BOOL success){
if (!success) {
// Handle the error.
[FlurryAnalytics logEvent:@"ERRORCouldNotOpenDataStore"];
} else {
LOG_GENERAL(2, @"UIMAnagedDocument loaded.");
if(opened){
opened();
}
}
}];
}
else {
[self saveToURL:docURL forSaveOperation:UIDocumentSaveForCreating completionHandler:^(BOOL success){
if (!success) {
// Handle the error.
[FlurryAnalytics logEvent:@"ERRORCouldNotCreateDataStore"];
} else {
LOG_GENERAL(2, @"UIMAnagedDocument loaded.");
[NSManagedObjectContext MR_setDefaultContext:self.managedObjectContext];
if(opened){
opened();
}
}
}];
}
}
-(void)handleError:(NSError *)error userInteractionPermitted:(BOOL)userInteractionPermitted
{
LOG_GENERAL(0, @"Error opening document %@", error);
[super handleError:error userInteractionPermitted:userInteractionPermitted];
}
- (void)save:(void(^)(BOOL))done
{
[self saveToURL:self.fileURL forSaveOperation:UIDocumentSaveForOverwriting completionHandler:done];
}
@end