Upload file to iCloud, sometimes file not found - ios

I want to upload some files to iCloud and use this:
FileDocument *doc = [[FileDocument alloc] initWithFileURL:des];
doc.data = [NSData dataWithContentsOfURL:src];
NSLog(#"Local url: %#", src);
NSLog(#"Remote url: %#", des);
[doc saveToURL:des forSaveOperation:UIDocumentSaveForCreating completionHandler:^(BOOL success) {
if (success) {
NSLog(#"Success");
} else {
NSLog(#"Fail ");
}
}];
After the success log, I open iCloud > Storage > Manage Storage on my iPad to check if file exist. Sometimes the file appear and sometimes not.

Related

Objective C: Move local core data store to icloud and vice versa

I'm having problems with this and read now several tutorials and also examples in one book, which however suggested more a deep copy which is too complicated for me. This iCloud stuff is anyway confusing. Did I get it right with this:
User enabling iCloud in app:
- Try to copy local store to icloud
- Deleting local store
User disabling iCloud in app:
- Try to copy store to local
- Remove ubiquitous content
- Remove local copy of icloud
Do I miss anything?
Extra questions: How can I "block" the app during copying and where should I place this "blocking" code?
This would be my code:
- (bool)moveStoreToICloud {
NSLog(<#NSString * _Nonnull format, ...#>)(#" called");
return [self moveStoreFileToICloud:self.store delete:YES backup:YES];
}
- (bool)moveStoreFileToICloud:(NSURL*)fileURL delete:(bool)shouldDelete backup:(bool)shouldBackup {
NSLog(#" called");
// Always make a backup of the local store before migrating to iCloud
if (shouldBackup)
[self backupLocalStore];
NSPersistentStoreCoordinator *migrationPSC = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:self.model];
// Open the existing local store using the original options
NSDictionary *options =
#{
NSMigratePersistentStoresAutomaticallyOption:#YES
,NSInferMappingModelAutomaticallyOption:#YES
,NSPersistentStoreUbiquitousContentNameKey:ubiquitousContentNameKey
//,NSPersistentStoreUbiquitousContentURLKey:#"ChangeLogs" // Optional since iOS7
};
id sourceStore = [migrationPSC addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:fileURL options:options error:nil];
if (!sourceStore) {
NSLog(#" failed to add old store");
return FALSE;
} else {
NSLog(#" Successfully added store to migrate");
bool moveSuccess = NO;
NSError *error;
NSLog(#" About to migrate the store...");
// Now migrate the store using the iCloud options
id migrationSuccess = [migrationPSC migratePersistentStore:sourceStore toURL:[_iCloudStore URL] options:options withType:NSSQLiteStoreType error:&error];
if (migrationSuccess) {
moveSuccess = YES;
NSLog(#"store successfully migrated");
// Now delete the local file
if (shouldDelete) {
NSLog(#" deleting local store");
[self destroyAllLocalDataForThisApplication];
} else {
NSLog(#" not deleting local store");
}
[self resetCoreData];
[self setupCoreData];
[[NSNotificationCenter defaultCenter] postNotificationName:#"SomethingChanged"
object:nil];
return TRUE;
}
else {
NSLog(#"Failed to migrate store: %#, %#", error, error.userInfo);
return FALSE;
}
}
return FALSE;
}
/*! Moves an iCloud store to local by migrating the iCloud store to a new local store and then removes the store from iCloud.
Note that even if it fails to remove the iCloud files it deletes the local copy. User may need to clean up orphaned iCloud files using a Mac!
#return Returns YES of file was migrated or NO if not.
*/
- (bool)moveStoreToLocal {
NSLog(#"moveStoreToLocal called");
// Lets use the existing PSC
NSPersistentStoreCoordinator *migrationPSC = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:self.model];
// Open the store
NSDictionary *options =
#{
NSMigratePersistentStoresAutomaticallyOption:#YES
,NSInferMappingModelAutomaticallyOption:#YES
,NSPersistentStoreUbiquitousContentNameKey:ubiquitousContentNameKey
//,NSPersistentStoreUbiquitousContentURLKey:#"ChangeLogs" // Optional since iOS7
};
id sourceStore = [migrationPSC addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:[_iCloudStore URL] options:options error:nil];
if (!sourceStore) {
NSLog(#" failed to add old store");
return FALSE;
} else {
NSLog(#" Successfully added store to migrate");
bool moveSuccess = NO;
NSError *error;
NSLog(#" About to migrate the store...");
id migrationSuccess = [migrationPSC migratePersistentStore:sourceStore toURL:[_store URL] options:options withType:NSSQLiteStoreType error:&error];
if (migrationSuccess) {
moveSuccess = YES;
NSLog(#"store successfully migrated");
// Now delete the local file
[self destroyAlliCloudDataForThisApplication];
[self resetCoreData];
[self setupCoreData];
[[NSNotificationCenter defaultCenter] postNotificationName:#"SomethingChanged"
object:nil];
return TRUE;
}
else {
NSLog(#"Failed to migrate store: %#, %#", error, error.userInfo);
return FALSE;
}
}
return TRUE;
}
#pragma mark - ICLOUD RESET
- (void)destroyAllLocalDataForThisApplication {
if (![[NSFileManager defaultManager] fileExistsAtPath:[[_store URL] path]]) {
NSLog(#"Skipped destroying content, _store.URL is %#",[[_store URL] path]);
return;
}
NSLog(#"\n\n\n\n\n **** Destroying ALL local content for this application, this could take a while... **** \n\n\n\n\n\n");
[self removeAllStoresFromCoordinator:_coordinator];
[self removeAllStoresFromCoordinator:_seedCoordinator];
_coordinator = nil;
_seedCoordinator = nil;
NSError *error;
if([[NSFileManager defaultManager] removeItemAtURL:_storeURL error:&error]){
NSLog(#"Local store successfully removed");
} else {
NSLog(#"\n\n **** FAILED to destroy this application's iCloud content at URL (%#) **** \n%#\n",[_store URL],error);
}
}
- (void)destroyAlliCloudDataForThisApplication {
if (![[NSFileManager defaultManager] fileExistsAtPath:[[_iCloudStore URL] path]]) {
NSLog(#"Skipped destroying iCloud content, _iCloudStore.URL is %#",[[_iCloudStore URL] path]);
return;
}
NSLog(#"\n\n\n\n\n **** Destroying ALL iCloud content for this application, this could take a while... **** \n\n\n\n\n\n");
[self removeAllStoresFromCoordinator:_coordinator];
[self removeAllStoresFromCoordinator:_seedCoordinator];
_coordinator = nil;
_seedCoordinator = nil;
NSDictionary *options =
#{
NSPersistentStoreUbiquitousContentNameKey:ubiquitousContentNameKey
//,NSPersistentStoreUbiquitousContentURLKey:#"ChangeLogs" // Optional since iOS7
};
NSError *error;
if ([NSPersistentStoreCoordinator removeUbiquitousContentAndPersistentStoreAtURL:[_iCloudStore URL]
options:options
error:&error]) {
NSLog(#"\n\n\n\n\n");
NSLog(#"* This application's iCloud content has been destroyed *");
NSLog(#"* On ALL devices, please delete any reference to this application in *");
NSLog(#"* Settings > iCloud > Storage & Backup > Manage Storage > Show All *");
NSLog(#"\n\n\n\n\n");
[[NSFileManager defaultManager] removeItemAtURL:[_iCloudStore URL] error:&error]
} else {
NSLog(#"\n\n **** FAILED to destroy this application's iCloud content at URL (%#) **** \n%#\n",[_iCloudStore URL],error);
}
}
If this is a new app, rethink your approach. Use CloudKit, or Azure, or Firebase.
iCloud Core Data never worked reliably. Thankfully Apple now realizes this. NSPersistentStoreUbiquitousContentNameKey is marked as deprecated as of iOS 10/macOS 12.12, as are the other iCloud Core Data symbols.

How download file google drive api ios

I tried to download file from google drive API since 3 day without success. I used this https://developers.google.com/drive/ios/devguide/files#reading_files.
But I can't understand what I need to put in *drive and *file?
I tried :
GTLDriveFile *file = #"fileText.txt"; (or I tried the url of my file on google drive...) The guide don't explain... And I didn't find real example.
GTLServiceDrive *drive = ...;
GTLDriveFile *file = ...;
NSString *url = [NSString stringWithFormat:#"https://www.googleapis.com/drive/v3/files/%#?alt=media",
file.identifier]
GTMSessionFetcher *fetcher = [drive.fetcherService fetcherWithURLString:url];
[fetcher beginFetchWithCompletionHandler:^(NSData *data, NSError *error) {
if (error == nil) {
NSLog(#"Retrieved file content");
// Do something with data
} else {
NSLog(#"An error occurred: %#", error);
}
}];
So I had search other code like but no one explain what I need to put in drive and file:
how to download file from google drive using objective c? (just this say it's url)
Google drive api download file for iOS
IOS: How to Download Google Docs files using ios google drive sdk API?
SOLUTION :
I had a problem of authorization with my scope, solved by total access to drive. I changed the scope (in quickstart code, look : "- (GTMOAuth2ViewControllerTouch *)createAuthController...")
-->NSArray *scopes = [NSArray arrayWithObjects:kGTLAuthScopeDrive, nil];
For download (inspired by quickstart example) :
// self.service is my GTLServiceDrive
// When the view appears, ensure that the Drive API service is authorized, and perform API calls.
- (void)viewDidAppear:(BOOL)animated {
if (!self.service.authorizer.canAuthorize) {
// Not yet authorized, request authorization by pushing the login UI onto the UI stack.
[self presentViewController:[self createAuthController] animated:YES completion:nil];
} else {
NSString *urltest = [NSString stringWithFormat:#"https://www.googleapis.com/drive/v3/files/%#?alt=media", identifier_file]; //the ID of my file in a string identifier_file
GTMSessionFetcher *fetcher = [self.service.fetcherService fetcherWithURLString:urltest]; // the request
// receive response and play it in web view:
[fetcher beginFetchWithCompletionHandler:^(NSData *data, NSError *errorrr) {
if (errorrr == nil) {
NSLog(#"Retrieved file content");
[webView_screen loadData:data MIMEType:#"application/pdf" textEncodingName:#"UTF-8" baseURL:nil]; //my file is a pdf
[webView_screen reload];
} else {
NSLog(#"An error occurred: %#", errorrr);
}
}];
}
}
If you want to save on the phone, you can look the Bala's code.
First fetch the file from Drive
driveFiles = [[NSMutableArray alloc] init];
for (GTLDriveFile *file in files.items) {
if ([file.mimeType isEqualToString:#"application/vnd.google-apps.folder"]) {
} else {
NSString *fileExtension = file.fileExtension;
if (fileExtension) {
if ([fileExtension isEqualToString:#"pdf"]) {
[driveFiles addObject:file];
}
}
}
}
And GTLDriveFile pass the object that you have in the array
GTLDriveFile *file=[driveFiles objectAtIndex:indexPath.row];
This is the code for download the file
NSString *link;
if (file.webContentLink) {
link = file.webContentLink;
} else if (file.embedLink) {
link = file.embedLink;
} else {
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"ERROR" message:#"File has no downloadable link" delegate:nil cancelButtonTitle:#"Ok" otherButtonTitles:nil, nil];
[alert show];
}
if (link) {
NSString *downloadUrl = file.downloadUrl;
GTMHTTPFetcher *fetcher = [self.driveService.fetcherService fetcherWithURLString:downloadUrl];
//async call to download the file data
[fetcher beginFetchWithCompletionHandler:^(NSData *data, NSError *error) {
if (error == nil) {
if (data) {
NSString *dirPath = [self directoryPathForSavingFile];
NSString *filePath = [dirPath stringByAppendingPathComponent:file.title];
[self saveFileJSONData:data forFileName:filePath withCompletionHandler:^(BOOL successStatus) {
// Adding skip attribute to avoid data sinking in iCloud
BOOL path = [[NSFileManager defaultManager] fileExistsAtPath:filePath];
if (path) {
NSLog(#"filePath %#", filePath);
}
}];
}
} else {
NSLog(#"An error occurred: %#", error);
}
}];
}
Code for Directory path for save the file
- (NSString *)directoryPathForSavingFile:(NSString *)directoryName {
NSString *applicationDirectory = [NSHomeDirectory() stringByAppendingPathComponent:#"Documents"];
applicationDirectory = [applicationDirectory stringByAppendingPathComponent:directoryName];
return applicationDirectory;
}

iOS: How can I create a backup copy of my core data base? And how to export/import that copy?

I want to offer the users of my app the possibility to create a backup of the core data database, especially in case he switches to a new device etc.
How would I do that? Especially how can I reimport that file? I mean let's say he makes a backup copy of the database, then changes a ton of stuff and wants to reset to the previous saved backup copy. How would I do that?
Thx!
Take a look at this sample app, it includes functions for making backups, copying backups to and from iCloud, emailing backups and importing backups from email.
http://ossh.com.au/design-and-technology/software-development/sample-library-style-ios-core-data-app-with-icloud-integration/
BTW it's much safer to use migratePersistentStore API to make/import backups if your are doing so to and from ICloud. Also be aware that the sample app assumes you are not using WAL mode which is the default mode for iOS 7. WAL mode uses multiple files which all need to be backed up or copied.
Here is a link to a video demonstrating the sample Apps backup and restore capabilities.
http://ossh.com.au/design-and-technology/software-development/sample-library-style-ios-core-data-app-with-icloud-integration/sample-apps-explanations/backup-files/
Here are the methods used to create copies for backup. Note that it is possible to open the store with multiple persistentStoreCoordinators so no need to close it down while you make a backup. Restoring it does obviously require the existing store to be removed first. Note that there is little difference between the two methods below except that the source store is opened with or without iCloud options.
/*! Creates a backup of the ICloud store
#return Returns YES of file was migrated or NO if not.
*/
- (bool)backupICloudStore {
FLOG(#"backupICloudStore called");
// Lets use the existing PSC
NSPersistentStoreCoordinator *migrationPSC = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:self.managedObjectModel];
// Open the store
id sourceStore = [migrationPSC addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:[self icloudStoreURL] options:[self icloudStoreOptions] error:nil];
if (!sourceStore) {
FLOG(#" failed to add old store");
migrationPSC = nil;
return FALSE;
} else {
FLOG(#" Successfully added store to migrate");
NSError *error;
FLOG(#" About to migrate the store...");
id migrationSuccess = [migrationPSC migratePersistentStore:sourceStore toURL:[self backupStoreURL] options:[self localStoreOptions] withType:NSSQLiteStoreType error:&error];
if (migrationSuccess) {
FLOG(#"store successfully backed up");
migrationPSC = nil;
// Now reset the backup preference
[[NSUserDefaults standardUserDefaults] setBool:NO forKey:_makeBackupPreferenceKey];
[[NSUserDefaults standardUserDefaults] synchronize];
return TRUE;
}
else {
FLOG(#"Failed to backup store: %#, %#", error, error.userInfo);
migrationPSC = nil;
return FALSE;
}
}
migrationPSC = nil;
return FALSE;
}
/*! Creates a backup of the Local store
#return Returns YES of file was migrated or NO if not.
*/
- (bool)backupLocalStore {
FLOG(#"backupLocalStore called");
// Lets use the existing PSC
NSPersistentStoreCoordinator *migrationPSC = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:self.managedObjectModel];
// Open the store
id sourceStore = [migrationPSC addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:[self localStoreURL] options:[self localStoreOptions] error:nil];
if (!sourceStore) {
FLOG(#" failed to add old store");
migrationPSC = nil;
return FALSE;
} else {
FLOG(#" Successfully added store to migrate");
NSError *error;
FLOG(#" About to migrate the store...");
id migrationSuccess = [migrationPSC migratePersistentStore:sourceStore toURL:[self backupStoreURL] options:[self localStoreOptions] withType:NSSQLiteStoreType error:&error];
if (migrationSuccess) {
FLOG(#"store successfully backed up");
migrationPSC = nil;
// Now reset the backup preference
[[NSUserDefaults standardUserDefaults] setBool:NO forKey:_makeBackupPreferenceKey];
[[NSUserDefaults standardUserDefaults] synchronize];
return TRUE;
}
else {
FLOG(#"Failed to backup store: %#, %#", error, error.userInfo);
migrationPSC = nil;
return FALSE;
}
}
migrationPSC = nil;
return FALSE;
}
/** Sets the selected file as the current store.
Creates a backup of the current store first.
#param fileURL The URL for the file to use.
*/
- (BOOL)restoreFile:(NSURL *)fileURL {
FLOG(#" called");
// Check if we are using iCloud
if (_isCloudEnabled) {
FLOG(#" using iCloud store so OK to restore");
NSURL *currentURL = [self storeURL];
FLOG(#" currentURL is %#", currentURL);
FLOG(#" URL to use is %#", fileURL);
[self saveContext];
[self backupCurrentStoreWithNoCheck];
// Close the current store and delete it
_persistentStoreCoordinator = nil;
_managedObjectContext = nil;
[self removeICloudStore];
[self moveStoreFileToICloud:fileURL delete:NO backup:NO];
} else {
FLOG(#" using local store so OK to restore");
NSURL *currentURL = [self storeURL];
FLOG(#" currentURL is %#", currentURL);
FLOG(#" URL to use is %#", fileURL);
[self saveContext];
[self backupCurrentStoreWithNoCheck];
// Close the current store and delete it
_persistentStoreCoordinator = nil;
_managedObjectContext = nil;
NSError *error = nil;
NSFileManager *fm = [[NSFileManager alloc] init];
// Delete the current store file
if ([fm fileExistsAtPath:[currentURL path]]) {
FLOG(#" target file exists");
if (![fm removeItemAtURL:currentURL error:&error]) {
FLOG(#" error unable to remove current store file");
NSLog(#"Error removing item Error: %#, %#", error, error.userInfo);
return FALSE;
} else {
FLOG(#" current store file removed");
}
}
//
//simply copy the file over
BOOL copySuccess = [fm copyItemAtPath:[fileURL path]
toPath:[currentURL path]
error:&error];
if (copySuccess) {
FLOG(#" replaced current store file successfully");
//[self postFileUpdateNotification];
} else {
FLOG(#"Error copying items Error: %#, %#", error, error.userInfo);
return FALSE;
}
}
// Now open the store again
[self openPersistentStore];
return TRUE;
}
Whatever the persistent store is that you use (binary, SQLite, etc.); it is just a file on the filesystem. You can make a copy of it whenever you want.
If you are using SQLite in iOS 7, be sure to make a copy of the other files associated with it as they are the journal files that go with it. If you are using binary then there will be only a single file.
If you just copy the file there is no import step, you just copy it back to restore it.
There are more advanced designs such as exporting the entire database to something that is portable, such as JSON but that is a different subject.
Update
Well I've used the standard Xcode core data template, so according to the code I've just checked I'm using SQLite. So how do I find all related files? Or could you show me with some example code how to copy and insert back the files needed?
You use NSFileManager to copy the files. You can look at the documents directory in your iOS simulator application to see the names of all the files. Or you could use NSFileManager to scan the documents directory, find everything that starts with the same file name (MyData.* for example) and copy that into a back up directory.
As for sample code, no; it is only a couple of lines of code once you look at the documentation for NSFileManager.
I created the following method with the help of Apple sample code. This will take a backup of core data files and place it to the path that you want.
Swift 5
/// Backing up store type to a new and unique location
/// The method is illustrated in the following code fragment, which shows how you can use migratePersistentStore to take a back up of a store and save it from one location to another.
/// If the old store type is XML, the example also converts the store to SQLite.
/// - Parameters:
/// - path: Where you want the backup to be done, please create a new unique directory with timestamp or the guid
/// - completion: Passes error in case of error or pass nil in case of success
class func backUpCoreDataFiles(path : URL, completion : #escaping (_ error : String?) -> ())
{
// Every time new container is a must as migratePersistentStore method will loose the reference to the container on migration
let container = NSPersistentContainer(name : "<YourDataModelName>")
container.loadPersistentStores
{ (storeDescription, error) in
if let error = error
{
fatalError("Failed to load store: \(error)")
}
}
let coordinator = container.persistentStoreCoordinator
let store = coordinator.persistentStores[0]
do
{
try coordinator.migratePersistentStore(store, to : path, options : nil, withType : NSSQLiteStoreType)
completion(nil)
}
catch
{
completion("\(Errors.coredataBackupError)\(error.localizedDescription)")
}
}

How to do incremental writing for UIDocument in iCloud?

I have UIDocument in iCloud ubiquitous container and I need to append data to file while saving document. I override readFromURL:: and writeContents::::: method according UIDocument documentation:
-(BOOL) writeContents:(id)contents toURL:(NSURL*)url forSaveOperation:(UIDocumentSaveOperation)saveOperation originalContentsURL:(NSURL*)originalContentsURL error:(NSError *__autoreleasing *)outError
{
NSFileCoordinator* coordinator = [[NSFileCoordinator alloc] initWithFilePresenter:self];
NSError* error = nil;
[coordinator coordinateWritingItemAtURL:url options:0 error:&error byAccessor:^(NSURL *newURL) {
NSData* data = contents; //correct, non-empty NSData
///[data writeToFile:newURL :] works, but overwrite original file
NSOutputStream* stream =[[NSOutputStream alloc] initWithURL:newURL append:YES];
if (stream)
{
NSInteger written = [stream write:data.bytes maxLength:data.length];
if (written != data.length)
{
//failed here, written == -1
NSLog(#"Write data to UIDocument failed: %#, error: %#", newURL, stream.streamError);
}
}
else
{
NSLog(#"Write data to iCloudDocument failed: %#", newURL);
}
}];
if (error)
{
NSLog(#"Coordinated write failed %#, error: %#", url, error);
*outError = error;
}
return error == nil;
}
Accessor block has different newURL, for example:
url: file:///private/var/mobile/Library/Mobile%20Documents/XXXXXXX~com~test~test/test.doc
newURL: file:///private/var/mobile/Applications/5631D484-7661-4E9E-A342-B25297FC0E18/tmp/(A%20Document%20Being%20Saved%20By%20test%20)/test.doc.
[stream write::] failed, because newURL file dosn't exists and I can't append data, only create file with all document's content.
Document editing code:
NSURL* url = [self.containerURL URLByAppendingPathComponent:kCloudDocumentName];
MyDocument* document = [[MyDocument alloc] initWithFileURL:url];
[document openWithCompletionHandler:^(BOOL success) {
if (success)
{
//update some document data
[self updateData:document completion:nil];
[document closeWithCompletionHandler:^(BOOL success) {
//failed here!
}];
}
}];
MyDocument exists in ubiquitous container at url and document has Normal state.
How I can do incremental writing in this case? Whats wrong?
After changing data in your UIDocumnet you can use:
-[UIDocumnet saveToURL:UIDocumnet.fileURL forSaveOperation:UIDocumentSaveForOverwriting completionHandler:nil];
Not sure, it's right or not but it works in my app. If it's wrong, correct me please somebody.
You may need to overwrite this method in your subclass of UIDocumnet:
- (id) contentsForType:(NSString *)typeName error:(NSError **)outError

iCloud UIManagedDocument EXC_BAD_ACCESS error after deleting app and reloading

I have an app that I'm making and it uses a UIManagedDocument to handle core data and iCloud. At the start of my app I Open the file and initialize the UIManagedDocument with the iCloud directory.
This works fine the first time I load the program and subsequent times but It is my understanding that because I use iCloud I should be able to delete the app and reload it and have it reload the data from the cloud.
When I delete the app and reload it its able to get the url and initialize the UIManagedDocument but once it gets to [document openWithCompletionHandler:^(BOOL success){}] the thread that was supposed to access the document comes back with EXC_BAD_ACCESS.
This is the code I use to setup the document with core data and the iCloud url is good. This is my first experience with iCloud. What am I doing wrong?
- (void)setupDocument
{
NSURL *url = [self iCloudDocumentsDirectory];
url = [url URLByAppendingPathComponent:#"ZJournalData"];
UIManagedDocument *document = [[ZManagedDocument alloc] initWithFileURL:url];
NSLog(#"%#", document);
[document.persistentStoreOptions setValue:[document.fileURL lastPathComponent] forKey:NSPersistentStoreUbiquitousContentNameKey];
[document.persistentStoreOptions setValue:[[self iCloudDirectory] URLByAppendingPathComponent:#"CoreDataLogs"] forKey:NSPersistentStoreUbiquitousContentURLKey];
if (![[NSFileManager defaultManager] fileExistsAtPath:[url path]]) {
[document saveToURL:url
forSaveOperation:UIDocumentSaveForCreating
completionHandler:^(BOOL success) {
if (success) {
self.managedObjectContext = document.managedObjectContext;
}
}];
} else if (document.documentState == UIDocumentStateClosed) {
[document openWithCompletionHandler:^(BOOL success) {
if (success) {
self.managedObjectContext = document.managedObjectContext;
}
}];
} else {
NSLog(#"%#", document);
self.managedObjectContext = document.managedObjectContext;
}
}

Resources