Search code examples
iosobjective-ciclouduidocument

UIDocument open/close behavior


I have a UIDocument based app, without iCloud support. The user is able to create documents, and save them to app's Document directory.

I have also created few "sample" documents, and passing them with the app's bundle. I want the user to be able to open sample documents the same way as they can open their own documents:

NSArray *samplesContent = [[NSBundle mainBundle] URLsForResourcesWithExtension:@"doco" subdirectory:@"Samples"];

for (NSURL *sampleURL in samplesContent) {
    Doco *doco = [[Doco alloc] initWithFileURL:sampleURL];
    [doco disableEditing];

    [doco openWithCompletionHandler:^(BOOL success) {
        if (success) {
            [self.docos addObject:doco];

            if (self.docos.count >= samplesContent.count) {
                [self.tableView reloadData];
            }
        } else DLog(@"Failed to open %@", [sampleURL pathExtension]);
     }];
}

What I am seeing is this:

  1. On viewDidLoad, docs array gets populated with sample docs and displayed in the tableView the first time app launches. No issues here, all is smooth and nice.
  2. Then I back out of the view with the following code to close all open docs:

    int count = 0;
    
    for (Doco *doco in self.docos) {
        if (doco.documentState == UIDocumentStateNormal) {
            [doco closeWithCompletionHandler:nil];
            count++;
        }
    }
    
    DLog(@"Closed %i docs", count);
    
  3. When I open the view again, the array of docs should get populated again and tableView re-populated, but nothing happens.

The completion handler below never gets called, although the URL is pointing to the same file and it is valid:

[doco openWithCompletionHandler:^(BOOL success) {}

I do not have this issue for user generated docs stored in Documents, so my assumption is that it has something to do with auto-save, that gets called on read-only bundle and fails

But I am sort of stuck on this part, any help will be appreciated.


Solution

  • If UIDocument is updated it will try to save changes on close. Since UIDocument was loaded from read-only bundle, I had to make sure that it does not get updated, otherwise close block returns success=NO, and document is not closed...