I have seen iCloud Document sample code for iOS and I used it to sync a uidocument to and from iCloud and now I am trying to sync iCloud with an nsdocument on a Mac OSX app which doesn’t have UIDocument.
I tried to change UIDocument to NSDocument but all the methods of syncing with icloud are different. I haven’t found any sample code or tutorials except for the documentation from apple which is very confusing and not well written.
For example, the method below, from UIDocument on iOS does not exist in NSDocument on OS X:
//doc is an instance of subclassed UIDocument
[doc openWithCompletionHandler:nil];
The Apple Documentation provides this code for OS X:
- (void)checkIfCloudAvaliable {
NSURL *ubiquityContainerURL = [[[NSFileManager defaultManager]
URLForUbiquityContainerIdentifier:nil]
URLByAppendingPathComponent:@"Documents"];
if (ubiquityContainerURL == nil) {
NSDictionary *dict = [NSDictionary dictionaryWithObjectsAndKeys:
NSLocalizedString(@"iCloud does not appear to be configured.", @""),
NSLocalizedFailureReasonErrorKey, nil];
NSError *error = [NSError errorWithDomain:@"Application" code:404
userInfo:dict];
[self presentError:error modalForWindow:[self windowForSheet] delegate:nil
didPresentSelector:NULL contextInfo:NULL];
return;
}
dest = [ubiquityContainerURL URLByAppendingPathComponent:
[[self fileURL] lastPathComponent]];
}
- (void)moveToOrFromCloud {
dispatch_queue_t globalQueue =
dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
dispatch_async(globalQueue, ^(void) {
NSFileManager *fileManager = [[NSFileManager alloc] init];
NSError *error = nil;
// Move the file.
BOOL success = [fileManager setUbiquitous:YES itemAtURL:[self fileURL]
destinationURL:dest error:&error];
dispatch_async(dispatch_get_main_queue(), ^(void) {
if (! success) {
[self presentError:error modalForWindow:[self windowForSheet]
delegate:nil didPresentSelector:NULL contextInfo:NULL];
}
});
});
[self setFileURL:dest];
[self setFileModificationDate:nil];
}
How can I sync between iOS and OS X (because NSDocument does not exists on iOS, and UIDocument does not exist on OS X)? Does anyone know where I can find a sample for Mac OSX (NSDocument syncing)?
I managed to get it working! Here’s my code from the subclassed nsdocument file on OS X:
Header file:
Implementation file:
and in the AppDelegate.m file:
The only thing that I haven’t got working is that if I change the data of the document on the iPad, the Mac app doesn’t call the
readFromDatamethod for to update from iCloud, does anyone know what I am missing?On iOS, the equivalent method,
loadFromContents, is called automatically on every change of theUIDocumentin iCloud. On OS X thereadFromDatais called once on load but never called again.Hope my code can help, for me it is working one way from Mac to iPad.