The iOS Dev Diary

iCloud in your iOS Apps – Part 3: Document Storage


Listen Later


In this part I’ll show you how to use your app’s ubiquitous folder to store arbitrary files in a user’s iCloud store. We’re not going to cover the UIDocument class here because it adds a layer of complexity to an already difficult subject, and for simple files it’s just not necessary. We’ll also cover how to download new files if iCloud changes have been detected.
There are two code snippets I’m referencing here: one is the method to retrieve your iCloud Documents folder (don’t forget to make it public like I did). This one goes into the AppDelegate.m:- (NSURL *)applicationCloudFolder:(NSString *)fileName {

// Team ID and Container ID
NSString *teamID = @"ABCDEF1234"; // add your own team ID here
NSString *bundleID = [NSBundle mainBundle].bundleIdentifier;
NSString *containerID = [NSString stringWithFormat:@"%@.%@", teamID, bundleID];

// URL to cloud folder
NSURL *cloudRootURL = [[NSFileManager defaultManager]URLForUbiquityContainerIdentifier:containerID];
NSURL *cloudDocuments = [cloudRootURL URLByAppendingPathComponent:@"Documents"];

// append our file name
cloudDocuments = [cloudDocuments URLByAppendingPathComponent:fileName];

return cloudDocuments;
}I’m also talking about the NSMetadataQuery which will detect changes in your iCloud Documents folder. This is a custom initialiser so you’ll need to create a property for it. Here’s the initialiser – in the video I’m using it in my ViewController class:- (NSMetadataQuery *)query {
if (!_query) {
_query = [[NSMetadataQuery alloc]init];

NSArray *scopes = @[NSMetadataQueryUbiquitousDocumentsScope];
_query.searchScopes = scopes;

NSPredicate *predicate = [NSPredicate predicateWithFormat:@"%K like %@", NSMetadataItemFSNameKey, @"*"];
_query.predicate = predicate;

if (![_query startQuery]) {
NSLog(@"Query didn't start... for whatever reason");
}
}
return _query;
}To kick this into action you’ll also need to add an observer under viewDidLoad:- (void)viewDidLoad
{
[super viewDidLoad];

// observe changes in iCloud folder
[[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(populateUI) name:NSMetadataQueryDidUpdateNotification object:self.query];
}
Watch the whole series

* Part 1 is about Setup and Prep Work
* Part 2 is about using Key/Value Storage
* Part 3 is about using Document Storage
* Part 4 is about using Core Data with iCloud
* and Part 5 is about the initial import into the Core Data store

Enjoy!

Watch the full course in one convenient playlist:Catch this episode on my iOS Dev Diary Podcast:
...more
View all episodesView all episodes
Download on the App Store

The iOS Dev DiaryBy Jay Versluis

  • 3
  • 3
  • 3
  • 3
  • 3

3

2 ratings