I have an iOS app that writes files to its iCloud ubiquity container. The container is specified in Signing & Capabilities as iCloud.com.myappbusiness.myappid where "com.myappbusiness.myappid" is the bundle identifier. It works most of the time but for some users (less than 1%) it stops working at some point, most likely after any update of my app. Device reboot or app reinstallation does not help. What seems to help is turning off iCloud for the app in the iOS Settings (at which point the app saves files to the device locally) and then turning it on again.
I cannot replicate the issue and have to rely on user feedback. I have tried various fixes over the past half a year, added retries after timeout, error handlers, tracing, etc. But the error always appears to someone after another app update.
I have narrowed it down to the three lines of code below that check for the existence of the app iCloud container:
NSFileManager* fileManager = [[NSFileManager alloc] init];
NSURL* containerUrl = [[fileManager URLForUbiquityContainerIdentifier:nil]
URLByAppendingPathComponent:@"Documents"];
BOOL doesExist = [fileManager fileExistsAtPath:containerUrl.path];
doesExist
returns NO
when the issue happens. I.e. the app does not see its container and it looks like it does not exist. The folder should exist as this happens to long term users that have used the app before. Regarding the containerUrl,
I can see it in the log that I get from the affected users and it is the correct path to the container, e.g. /private/var/mobile/Library/Mobile Documents/iCloud~com~myappbusiness~myappid/Documents
I have tried the code above as it is and also within a file coordinator handler:
[[[NSFileCoordinator alloc] initWithFilePresenter:nil] coordinateWritingItemAtURL:targetFileUrl
options:NSFileCoordinatorWritingForReplacing error:&error
byAccessor:^(NSURL * _Nonnull newURL) { ... the code here ... }];
I have run out of ideas what else to try. Is there anything obviously wrong with this approach or am I missing something in the code here? Is this a permission issue? Do I need to recreate the Documents folder if it's not accessible?