UIManagedDocument - How to deal with UIDocumentStateSavingError?

Go To StackoverFlow.com

2

I am working on my first iCloud App. After working for a while the app cannot access a UIManagedDocument any more due to an "UIDocumentStateSavingError". Is there any way to actually find out what error occurred?

This is my code to create the UIManagedDocument:

dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
    iCloudURL = [[NSFileManager defaultManager] URLForUbiquityContainerIdentifier:nil];

    if (iCloudURL == nil) {
        dispatch_async(dispatch_get_main_queue(), ^{
            [self iCloudNotAvailable];
        });
        return;
    }


    iCloudDocumentsURL = [iCloudURL URLByAppendingPathComponent:@"Documents"];
    iCloudCoreDataLogFilesURL = [iCloudURL URLByAppendingPathComponent:@"TransactionLogs"];

    NSURL *url = [iCloudDocumentsURL URLByAppendingPathComponent:@"CloudDatabase"];
    iCloudDatabaseDocument = [[UIManagedDocument alloc] initWithFileURL:url];

    NSMutableDictionary *options = [NSMutableDictionary dictionary];

    NSString *name = [iCloudDatabaseDocument.fileURL lastPathComponent];
    [options setObject:name forKey:NSPersistentStoreUbiquitousContentNameKey];
    [options setObject:iCloudCoreDataLogFilesURL forKey:NSPersistentStoreUbiquitousContentURLKey];

    iCloudDatabaseDocument.persistentStoreOptions = options;

    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(documentContentsChanged:) name:NSPersistentStoreDidImportUbiquitousContentChangesNotification object:iCloudDatabaseDocument.managedObjectContext.persistentStoreCoordinator];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(documentStateChanged:) name:UIDocumentStateChangedNotification object:iCloudDatabaseDocument];


    if ([[NSFileManager defaultManager] fileExistsAtPath:[iCloudDatabaseDocument.fileURL path]]) {
        // This is true, the document exists.
        if (iCloudDatabaseDocument.documentState == UIDocumentStateClosed) {
            [iCloudDatabaseDocument openWithCompletionHandler:^(BOOL success) {
                if (success) {
                    dispatch_async(dispatch_get_main_queue(), ^{
                        [self documentConnectionIsReady];
                    });
                } else {
                    dispatch_async(dispatch_get_main_queue(), ^{
                        [self connectionError:iCloudConnectionErrorFailedToOpen];
                    });
                }
            }];                    
        } else if (iCloudDatabaseDocument.documentState == UIDocumentStateNormal) {
            ...
        }      
    } else {
        ...               
    }           
});

The Document already exists and thus openWithCompletionHandler: is called on the document. This fails and the UIDocumentStateChangedNotification is fired which shows a document states of 5: UIDocumentStateClosed and UIDocumentStateSavingError

After this the completion block gets called. What is correct way to proceed from here? Is there any way to find out what went wrong and what kind of error occurred?

I tried to re-open the document in the completion block but the result is the same.

I guess I could solve the problem by just deleting the file and recreate it. But this is obviously not an option once the app will be out in the store. I would like to know what is going wrong and give the user an appropriator way to handle the problem.

I already checked other questions here handling the UIDocumentStateSavingError (there a not a lot of them) but the seem not to be applicable for the problem here.

Any idea how I can find out what the problem is? I cannot belive that the API tells you "Something went wrong during saving but I will not tell you what!"

2012-04-04 17:04
by Andrei Herford


5

You can query the documentState in the completion handler. Unfortunately, if you want the exact error, the only way to get it is to subclass and override handleError:userInteractionPermitted:

Maybe something like this would help (typed freehand without compiler)...

@interface MyManagedDocument : UIManagedDocument
 - (void)handleError:(NSError *)error
         userInteractionPermitted:(BOOL)userInteractionPermitted;
@property (nonatomic, strong) NSError *lastError;
@end

@implementation MyManagedDocument
@synthesize lastError = _lastError;
 - (void)handleError:(NSError *)error
         userInteractionPermitted:(BOOL)userInteractionPermitted
{
    self.lastError = error;
    [super handleError:error
           userInteractionPermitted:userInteractionPermitted];
}
@end

Then in you can create it like this...

iCloudDatabaseDocument = [[UIManagedDocument alloc] initWithFileURL:url];

and use it in the completion handler like this...

        [iCloudDatabaseDocument openWithCompletionHandler:^(BOOL success) {
            if (success) {
                dispatch_async(dispatch_get_main_queue(), ^{
                    [self documentConnectionIsReady];
                });
            } else {
                dispatch_async(dispatch_get_main_queue(), ^{
                    [self connectionError:iCloudConnectionErrorFailedToOpen
                                withError:iCloudDatabaseDocument.lastError];
                });
            }
        }];                    
2012-04-12 15:10
by Jody Hagins


1

Based on @JodyHagins excellent snippet, I have made a UIDocument subclass.

@interface SSDocument : UIDocument
- (void)openWithSuccess:(void (^)())successBlock
           failureBlock:(void (^)(NSError *error))failureBlock;
@end


@interface SSDocument ()
@property (nonatomic, strong) NSError *lastError;
@end

@implementation SSDocument

- (void)handleError:(NSError *)error userInteractionPermitted:(BOOL)userInteractionPermitted {
    self.lastError = error;
    [super handleError:error userInteractionPermitted:userInteractionPermitted];
}

- (void)clearLastError {
    self.lastError = nil;
}

- (void)openWithSuccess:(void (^)())successBlock failureBlock:(void (^)(NSError *error))failureBlock {
    NSParameterAssert(successBlock);
    NSParameterAssert(failureBlock);
    [self clearLastError];
    [self openWithCompletionHandler:^(BOOL success) {
        if (success) {
            successBlock();
        } else {
            NSError *error = self.lastError;
            [self clearLastError];
            failureBlock(error);
        }
    }];
}

@end
2013-07-01 18:06
by neoneye
Ads