Search code examples
iosobjective-cicloud

Sync app data with iCloud on request


I want to store some of my application data in iCloud, and I want it to be saved when the application is going to the background or is shut down.

I have a MyDocument class, which is written in accordance with this Apple tutorial. In fact, I do this:

// this function called from applicationDidEnterBackground
void SaveICloudData( const char *rawData )
{
    MyDocument *doc = AppDelegate.getICloudDocument;     // MyDocument is subclass of UIDocument, like in tutorial

    NSString *str = [[NSString alloc] initWithUTF8String:rawData];
    [doc setDocumentText:str];
}

My app goes to the background and is synchronized only when I turn it on again. But I want to synchronize my data with iCloud manually. How can I do this?


Solution

  • Before exiting, UIDocument checks if the document hasUnsavedChanges. If YES, saving is invoked.
    You are setting the document text in the applicationDidEnterBackground delegate method, which is probably too late.

    From the method docs:

    You should perform any tasks relating to adjusting your user interface before this method exits but other tasks (such as saving state) should be moved to a concurrent dispatch queue or secondary thread as needed. Because it's likely any background tasks you start in applicationDidEnterBackground: will not run until after that method exits, you should request additional background execution time before starting those tasks. In other words, first call beginBackgroundTaskWithExpirationHandler: and then run the task on a dispatch queue or secondary thread.