Ronald Bledsoe
Ronald Bledsoe

Reputation: 31

How to copy file in iCloud to app sandbox using File Manager

I have a file in the Cloud 15.2 kb. I cannot copy it back to the app sandbox. My code is listed below. Any help is appreciated

    NSURL *ubiq = [[NSFileManager defaultManager]
                   URLForUbiquityContainerIdentifier:nil];
if (ubiq)
    {
    NSError *error = nil;
    NSFileManager *fileManager = [NSFileManager defaultManager];
    NSURL *cloudContainerURL = [fileManager URLForUbiquityContainerIdentifier:nil]:
    NSURL*dirURL=[cloudContainerURL URLByAppendingPathComponent:@"Documents" isDirectory:YES];
    [fileManager createDirectoryAtURL:dirURL withIntermediateDirectories:NO  attributes:nil error:&error];
     NSURL *icloudURL = [dirURL URLByAppendingPathComponent:@"Passwords File.txt"];

    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsPath = [paths objectAtIndex:0];

    // Destination path
    NSString *fileInDocumentsPath = [documentsPath  stringByAppendingPathComponent:@"Passwords File.txt"];
     NSURL* sandboxDocumentURL = [NSURL fileURLWithPath:fileInDocumentsPath];

  [[ NSFileManager defaultManager ] copyItemAtURL:icloudURL toURL:sandboxDocumentURL error:&error ];

Upvotes: 0

Views: 1157

Answers (1)

Tom Harrington
Tom Harrington

Reputation: 70976

You can't just copy a file from iCloud to a local directory, because the file might not exist on the local device yet. Your app's iCloud files are only downloaded on demand, and you haven't done anything to create that demand. As a result, there's no source file to copy. Even if you know the file is in the cloud, you can't access it until it exists locally.

If you were checking the error parameter you passed to copyItemAtURL:toURL:error: you might already know this.

To download the file you use -[NSFileManager startDownloadingUbiquitousItemAtURL:error:]. That begins the process. You can find out when the download finishes using one of:

  • NSMetadataQuery, which will post an update when the download finishes, or
  • NSFileManager, which won't notify you but which does have a NSURLUbiquitousItemIsDownloadedKey flag that you can check.

Upvotes: 1

Related Questions