-
Notifications
You must be signed in to change notification settings - Fork 0
/
MKDocumentSync.m
247 lines (187 loc) · 9.73 KB
/
MKDocumentSync.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
//
// MKDocumentSync.m
// MKDocumentSync
//
// Created by Mugunth Kumar on 6/2/12.
// Copyright 2012 Steinlogic Consulting and Training Pte Ltd. All rights reserved.
// File created using Singleton XCode Template by Mugunth Kumar (http://blog.mugunthkumar.com)
// More information about this template on the post http://mk.sg/89
// Permission granted to do anything, commercial/non-commercial with this file apart from removing the line/URL above
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
// As a side note, you might also consider
// 1) tweeting about this mentioning @mugunthkumar
// 2) A paypal donation to [email protected]
#import "MKDocumentSync.h"
@interface MKDocumentSync (/*Private Methods*/)
-(void) pullFromiCloud;
-(void) pushToiCloud;
-(NSString*) documentsDirectory;
@property (strong, nonatomic) NSMetadataQuery *metadataQuery;
@end
@implementation MKDocumentSync
@synthesize metadataQuery = metadataQuery;
#pragma mark -
#pragma mark Singleton Methods
+ (MKDocumentSync*)sharedInstance {
static MKDocumentSync *_sharedInstance;
if(!_sharedInstance) {
static dispatch_once_t oncePredicate;
dispatch_once(&oncePredicate, ^{
_sharedInstance = [[super allocWithZone:nil] init];
});
}
return _sharedInstance;
}
+ (id)allocWithZone:(NSZone *)zone {
return [self sharedInstance];
}
- (id)copyWithZone:(NSZone *)zone {
return self;
}
-(void) startSync {
if(NSClassFromString(@"NSUbiquitousKeyValueStore")) { // is iOS 5?
NSURL *iCloudFirstContainer = [[NSFileManager defaultManager] URLForUbiquityContainerIdentifier:nil];
if(iCloudFirstContainer) { // is iCloud enabled
[self pullFromiCloud];
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_LOW, 0), ^{
[self pushToiCloud];
});
} else {
DLog(@"iCloud Document Sync not enabled");
}
}
else {
DLog(@"Not an iOS 5 device");
}
}
#pragma mark -
#pragma mark Custom Methods
// Add your custom methods here
- (void)queryDidFinishGathering:(NSNotification *)notification {
for(NSMetadataItem *item in self.metadataQuery.results) {
NSURL *url = [item valueForAttribute:NSMetadataItemURLKey];
NSError *error = nil;
DLog(@"Downloading [%@] from iCloud", url);
NSNumber *isIniCloud = nil;
if ([url getResourceValue:&isIniCloud forKey:NSURLIsUbiquitousItemKey error:nil]) {
// If the item is in iCloud, see if it is downloaded.
if ([isIniCloud boolValue]) {
NSNumber* isDownloaded = nil;
error = nil;
// If the item is in iCloud, see if it is downloaded.
if ([url getResourceValue:&isDownloaded forKey:NSURLUbiquitousItemIsDownloadedKey error:&error]) {
if(error) DLog(@"Cannot check iCloud sync status of file [%@]", error);
if (![isDownloaded boolValue]) {
error = nil;
[[NSFileManager defaultManager] startDownloadingUbiquitousItemAtURL:url error:&error];
if(error) DLog(@"Cannot start downloading from iCloud [%@]", error);
}
}
error = nil;
NSNumber* isConflicted = nil;
if ([url getResourceValue:&isConflicted forKey:NSURLUbiquitousItemHasUnresolvedConflictsKey error:&error]) {
if ([isConflicted boolValue]) {
DLog(@"%@ is in conflict. Removing from iCloud", url);
NSString *fileName = [url lastPathComponent];
NSString *documentsDirectoryPath = [[self documentsDirectory] stringByAppendingPathComponent:fileName];
[[NSFileManager defaultManager] moveItemAtURL:url toURL:[NSURL fileURLWithPath:documentsDirectoryPath]
error:&error];
if(error) DLog(@"Moving conflicted file failed: [%@]", error);
error = nil;
[[NSFileManager defaultManager] evictUbiquitousItemAtURL:url error:&error];
if(error) DLog(@"Evicting conflicted file failed: [%@]", error);
}
}
}
}
}
[self.metadataQuery disableUpdates];
[self.metadataQuery stopQuery];
[[NSNotificationCenter defaultCenter] removeObserver:self
name:NSMetadataQueryDidFinishGatheringNotification
object:self.metadataQuery];
self.metadataQuery = nil; // we're done with it
}
-(void) pullFromiCloud {
self.metadataQuery = [[NSMetadataQuery alloc] init];
self.metadataQuery.searchScopes = [NSArray arrayWithObject:NSMetadataQueryUbiquitousDocumentsScope];
self.metadataQuery.predicate = [NSPredicate predicateWithFormat:@"%K LIKE '*'", NSMetadataItemFSNameKey];
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(queryDidFinishGathering:)
name:NSMetadataQueryDidFinishGatheringNotification
object:self.metadataQuery];
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(queryDidFinishGathering:)
name:NSMetadataQueryDidUpdateNotification
object:self.metadataQuery];
[self.metadataQuery startQuery];
}
-(void) pushToiCloud {
NSString *docsDirectory = [self documentsDirectory];
NSArray *listOfFiles = [self filesInDirectory:docsDirectory];
for(NSString *filePath in listOfFiles) {
NSURL *fileURL = [NSURL fileURLWithPath:filePath];
NSString *relativePath = [filePath stringByReplacingOccurrencesOfString:docsDirectory withString:@""];
relativePath = [relativePath substringFromIndex:1];
NSURL *iCloudFirstContainer = [[NSFileManager defaultManager] URLForUbiquityContainerIdentifier:nil];
NSURL *iCloudDestinationURL = [[iCloudFirstContainer URLByAppendingPathComponent:@"Documents"] URLByAppendingPathComponent:relativePath];
NSURL *directoryURL = [iCloudDestinationURL URLByDeletingLastPathComponent];
NSError *error = nil;
[[NSFileManager defaultManager] createDirectoryAtURL:directoryURL withIntermediateDirectories:YES attributes:nil error:&error];
if(error) DLog(@"Unable to create iCloud local directory [%@]", error);
error = nil;
[[NSFileManager defaultManager] setUbiquitous:YES
itemAtURL:fileURL
destinationURL:iCloudDestinationURL
error:&error];
if(error) DLog(@"%@", error);
DLog(@"Moving [%@] to iCloud location at [%@]", fileURL, iCloudDestinationURL);
}
}
-(NSString*) documentsDirectory {
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *docsDirectory = [paths objectAtIndex:0];
return docsDirectory;
}
-(NSString*) iCloudLocalDocumentDirectory {
NSURL *iCloudFirstContainer = [[NSFileManager defaultManager] URLForUbiquityContainerIdentifier:nil];
NSURL *iCloudDocsURL = [iCloudFirstContainer URLByAppendingPathComponent:@"Documents"];
return [iCloudDocsURL path];
}
-(NSMutableArray*) filesIniCloudDirectory {
return [self filesInDirectory:[self iCloudLocalDocumentDirectory]];
}
-(NSMutableArray*) filesInDirectory: (NSString*) directoryName
{
NSMutableArray *listOfFiles = [NSMutableArray array];
NSDirectoryEnumerator *sourceDirectoryFilePathEnumerator = [[NSFileManager defaultManager] enumeratorAtPath: directoryName];
NSString *fileName;
while ((fileName = [sourceDirectoryFilePathEnumerator nextObject])) {
NSDictionary* sourceDirectoryFileAttributes = [sourceDirectoryFilePathEnumerator fileAttributes];
NSString* sourceDirectoryFileType = [sourceDirectoryFileAttributes objectForKey:NSFileType];
if ([sourceDirectoryFileType isEqualToString:NSFileTypeRegular] == YES) {
NSString *absPath = [directoryName stringByAppendingPathComponent:fileName];
[listOfFiles addObject:absPath];
}
else if([sourceDirectoryFileType isEqualToString:NSFileTypeDirectory] == YES) {
[listOfFiles addObjectsFromArray:[self filesInDirectory:fileName]];
}
}
return listOfFiles;
}
@end