Question

In my app, I am trying to do a simple thing - save a txt file and an image file into iCloud and then retrieve it back to open it on the app.

Right now, I can save both txt and image files into iCloud - no problem. I can even pull the URLs and the file names of the documents from iCloud - no problem there as well. But my question is, how do I open the txt file? What a sample code to open a txt file from iCloud and get the text contents? My txt file document is a subclass of UIDocument, if that helps.

Was it helpful?

Solution

well I notice it's like 4 months after you asked this question. Maybe this will be help for other seeking souls here.

Basically, on iOS you open a UIDocument first by querying all documents, then by opening what iCloud responds you with. Here's how you start a query:

NSURL *baseURL = [[NSFileManager defaultManager] URLForUbiquityContainerIdentifier:nil];
if (baseURL)
{
    _metadataQuery = [[NSMetadataQuery alloc] init];
    [_metadataQuery setSearchScopes:[NSArray arrayWithObject:NSMetadataQueryUbiquitousDocumentsScope]];

    NSPredicate *predicate = [NSPredicate predicateWithFormat:@"%K like '*'", NSMetadataItemFSNameKey];
    [_metadataQuery setPredicate:predicate];

    CL_DLog(@"Start query - %d",[_metadataQuery startQuery]);
}

Before doing code above, subscribe to these notifications to receive response

    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(queryDidFinish:) name:NSMetadataQueryDidFinishGatheringNotification object:_metadataQuery];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(queryDidFinish:) name:NSMetadataQueryDidUpdateNotification object:_metadataQuery];

Then in your response you can open the document

YourUIDocumentClassName *document = [[YourUIDocumentClassName alloc] initWithFileURL:documentURL];

if ([document documentState] != UIDocumentStateClosed)
{
    CL_DLog(@"FYI - metadata document state is not StateClosed.");
}

[document openWithCompletionHandler:^(BOOL success) {
....

You can check Apple's session on icloud and UIDocument https://developer.apple.com/videos/wwdc/2012/?id=218

Hope it helps.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top