iCloud wont sync on the first launch

2019-07-25 17:31发布

问题:

I have a bug where my app wont pull icloud inforamtion on the first launch but it does on the subsequent tries. here is my code to load a file from icloud.

void DLC::loadFromiCloud(std::string fileName){

NSURL *mUbiqUrl = [[NSFileManager defaultManager] URLForUbiquityContainerIdentifier:nil];

if (mUbiqUrl) {

std::string fullPath = getLibraryPath_iOS() + fileName;

NSString* restorePath = [NSString stringWithUTF8String:(fullPath.c_str())];
    NSError *error = nil;
    NSURL *fileToDownload = [mUbiqUrl URLByAppendingPathComponent:[NSString stringWithUTF8String:(fileName.c_str())]];
    [[NSFileManager defaultManager] startDownloadingUbiquitousItemAtURL:fileToDownload 
                                                error:&error];
    if (error != nil)
    {
        NSLog(@"iCloud L2 error: %@", [error localizedDescription]);
    }
    else 
    {
        NSNumber*  isIniCloud = nil;
        if ([fileToDownload getResourceValue:&isIniCloud forKey:NSURLIsUbiquitousItemKey error:nil])
        {
            // If the item is in iCloud, see if it is downloaded.
            if ([isIniCloud boolValue]) 
            {
                NSNumber*  isDownloaded = nil;
                if ([fileToDownload getResourceValue:&isDownloaded forKey:NSURLUbiquitousItemIsDownloadedKey error:nil]) 
                {
                    if ([isDownloaded boolValue])
                    {
                        NSString *fileData = [NSString stringWithContentsOfURL:fileToDownload encoding:NSUTF8StringEncoding error:&error];
                        //NSLog(@"iCloud data: %@", fileData);
                        [fileData writeToFile:restorePath atomically:YES encoding:NSUTF8StringEncoding error:&error];
                        if (error)
                        {
                            NSLog(@"iCloud L3 error: %@", [error localizedDescription]);
                        }
                    }
                }
            }
        }
    }
}}