Search code examples
iosfilemobileios-extensions

Cannot write to path within iOS document provider


I am trying to write an iOS document provider (iOS 9), and have used the available Apple documentation and code as a stating point. However, I am running into a strange issue where I cannot write to the location pointed to by the storage URL. I am testing an import operation.

Here is the value I am getting for documentStorageURL:

file:///private/var/mobile/Containers/Shared/AppGroup/4F0A350D-8CD7-4A25-83ED-2C6120CD30FA/File%20Provider%20Storage/

However when I try to write to that location, I get the following error:

Error Domain=NSCocoaErrorDomain Code=4 "The file “test.txt” doesn’t exist." UserInfo={NSFilePath=/private/var/mobile/Containers/Shared/AppGroup/4F0A350D-8CD7-4A25-83ED-2C6120CD30FA/File Provider Storage/test.txt, NSUnderlyingError=0x15f5ba010 {Error Domain=NSPOSIXErrorDomain Code=2 "No such file or directory"}}

One thing that is odd is the containerURL returned from containerURLForSecurityApplicationGroupIdentifier is actually different:

file:///private/var/mobile/Containers/Shared/AppGroup/A92110D1-D0B9-4DA7-8048-A4C63FF931D5/

I am actually able to write to this latter path and read it back to verify, but then when I call dismissGrantingAccessToURL I get an error that says the path I returned back is not the documentStorageURL.

Here is the relevant code which is being called after I press a button in the UI of the document provider:

NSURL *container = [[NSFileManager defaultManager] containerURLForSecurityApplicationGroupIdentifier:@"group.com.jdw.DocumentProvider"]; 
NSLog(@"container url = %@", container);
NSLog(@"openDocument: storage uRL = %@", self.documentStorageURL);
NSURL* documentURL;

if (self.documentStorageURL != nil)
    documentURL = [self.documentStorageURL URLByAppendingPathComponent:@"test.txt"];
else
    documentURL= [container URLByAppendingPathComponent:@"test.txt"];

NSString *fileName = [documentURL path];

NSString *contents = @"this is a dynamically created text file";

NSLog(@"write to file = %@", fileName);

NSError *err;

[contents writeToFile:fileName 
          atomically:NO 
            encoding:NSStringEncodingConversionAllowLossy 
                error:&err];

NSLog(@"write: error = %@", err);

Solution

  • I tried this again today and things magically worked, without any significant code changes that should have fixed the issue. I did reset the iPhone though.

    I'm pretty sure this is a iOS or XCode bug. For reference, I'm using XCode 7.2 and iOS 9.2