Correction: I should have posted this as the reading and writing code:
void writeToiCloud(void) {
NSFileManager *fman = [NSFileManager defaultManager];
NSURL *urlDrive = [fman URLForUbiquityContainerIdentifier: nil];
NSURL *urlDocs = [urlDrive URLByAppendingPathComponent:@"Documents"];
if( ! [fman fileExistsAtPath: urlDocs.path] ) { //..need to create the Docs directory
NSError *err00 = nil;
@try {
[fman createDirectoryAtURL: urlDocs withIntermediateDirectories:true
attributes:nil error:&err00];
} @catch (NSException *except) {
NSLog(@"Exception creating directory %@", except);
}
} //..directory is now created if needed
NSURL *urlFile = [urlDocs URLByAppendingPathComponent:@"hello.txt"];
NSData *fdata = [@"Hello world" dataUsingEncoding: NSUTF8StringEncoding];
NSError *errorReturn = nil;
Boolean ret = [fdata writeToURL: urlFile options: NSDataWritingAtomic error: &errorReturn];
NSLog(@"returned %1d, error=%@", ret?1:0, errorReturn); //always says "1 error=(nil)"
}
void readFromiCloud(void) {
NSFileManager *fman = [NSFileManager defaultManager];
NSURL *urlDrive = [fman URLForUbiquityContainerIdentifier: nil];
NSURL *urlDocs = [urlDrive URLByAppendingPathComponent:@"Documents"];
NSURL *urlFile = [urlDocs URLByAppendingPathComponent:@"hello.txt"];
if([fman fileExistsAtPath: urlFile.path]) {
NSString *fullFN = [localDocsDirectory() stringByAppendingPathComponent: @"hello-Local.txt"];
NSURL *destURL = [NSURL fileURLWithPath: fullFN];
@try {
[fman copyItemAtURL: urlFile toURL:destURL error:&errReading];
NSLog(@"file copied from iCloud to local");
} @catch(NSException *exc) {
NSLog(@"copyItem threw %@", exc);
}
} else {NSLog(@"file %@ DOES NOT EXIST!", urlFile);}
}
Topic:
Community
SubTopic:
Apple Developers
Tags: