Upgrade to Pro — share decks privately, control downloads, hide ads and more …

Core Data to UIDocument for iCloud

Core Data to UIDocument for iCloud

These slides are from a talk I did for CocoaHeads Belgium. I talked about how I moved my “B-list” shopping list app for iOS from Core Data to UIDocument for syncing lists with iCloud.

Steven Vandeweghe

April 30, 2013

Transcript

29 slides
  1. Documents folder Create a /Documents folder in the iCloud container.

    I you don’t store files in /Documents, you won’t see them individually.
  2. UIDocument can read and write - (BOOL)loadFromContents:(id)contents ofType:(NSString *)typeName error:(NSError

    **)outError - (id)contentsForType:(NSString *)typeName error:(NSError **)outError id: NSData or NSFileWrapper
  3. UIDocument has a life cycle - (void)saveToURL:(NSURL *)url forSaveOperation: (UIDocumentSaveOperation)saveOperation

    completionHandler:(void (^)(BOOL success))completionHandler - (void)openWithCompletionHandler:(void (^)(BOOL success))completionHandler - (void)closeWithCompletionHandler:(void (^)(BOOL success))completionHandler
  4. About that URL... it can be local documentURL = [NSURL

    fileURLWithPath:NSHomeDirectory()]; or in iCloud documentURL = [[NSFileManager defaultManager] URLForUbiquityContainerIdentifier:nil]; → don’t call this on the main thread!
  5. Is this thing on? dispatch_async(dispatch_get_global_queue(...), ^{ NSFileManager *fm = [NSFileManager

    defaultManager]; ! ! url = [fm URLForUbiquityContainerIdentifier:nil]; }); iOS 6 NSFileManager *fm = [NSFileManager defaultManager]; id token = [fm ubiquityIdentityToken]; → you can call this on the main thread
  6. NSMetadataQuery _query = [[NSMetadataQuery alloc] init]; _query.searchScopes = @[NSMetadataQueryUbiquitousDocumentsScope]; _query.predicate

    = [NSPredicate predicateWithFormat:@"%K ENDSWITH '.blist'", NSMetadataItemFSNameKey]; [_query setNotificationBatchingInterval:0.5]; [_query startQuery]; → NSMetadataQueryDidFinishGatheringNotification → NSMetadataQueryDidUpdateNotification [[_query resultAtIndex:index] valueForAttribute:NSMetadataItemURLKey]; [_query disableUpdates]; [_query enableUpdates];
  7. Conflicts NSFileVersion *currentVersion = [NSFileVersion currentVersionOfItemAtURL:doc.fileURL]; NSFileVersion NSArray *conflictVersions =

    [[NSFileVersion unresolvedConflictVersionsOfItemAtURL:…] + (BOOL)removeOtherVersionsOfItemAtURL:(NSURL *)inFileURL error:(NSError **)outError @property (getter=isResolved) BOOL resolved @property(readonly) NSURL *URL
  8. Coordinated file operations NSFileCoordinator [fc coordinateWritingItemAtURL:documentURL ! ! ! !

    ! ! ! options:NSFileCoordinatorWritingForDeleting ! ! ! ! ! ! ! error:&error ! ! ! ! ! ! ! byAccessor:^(NSURL *newURL) { ! NSError *e; ! NSFileManager *fm = [[NSFileManager alloc] init]; ! BOOL success = [fm removeItemAtURL:newURL error:&e]; ! if (!success) { ! ! ... ! } }];

More Decks by Steven Vandeweghe

Other Decks in Programming