Добавил:
Upload Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:
Beginning iOS5 Development.pdf
Скачиваний:
7
Добавлен:
09.05.2015
Размер:
15.6 Mб
Скачать

520

CHAPTER 14: Hey! You! Get onto iCloud!

After that, we create and configure an instance of NSMetadataQuery:

self.query = [[NSMetadataQuery alloc] init];

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

query.searchScopes = [NSArray arrayWithObject: NSMetadataQueryUbiquitousDocumentsScope];

This class was originally written for use with the Spotlight search facility on Mac OS X, but it’s now doing extra duty as a way to let iOS apps search iCloud directories. We give the query a predicate, which limits its search results to include only those with the correct sort of file name, and we give it a search scope that limits it to look just within the Documents folder in the app’s iCloud storage. Then we set up some notifications to let us know when the query is complete, and fire up the query.

Now, we need to implement the method that those notifications call when the query is done. Add this method just below the reloadFiles method:

- (void)updateUbiquitousDocuments:(NSNotification *)notification { self.documentURLs = [NSMutableArray array]; self.documentFilenames = [NSMutableArray array];

NSLog(@"updateUbiquitousDocuments, results = %@", self.query.results); NSArray *results = [self.query.results sortedArrayUsingComparator:

^NSComparisonResult(id obj1, id obj2) { NSMetadataItem *item1 = obj1; NSMetadataItem *item2 = obj2;

return [[item2 valueForAttribute:NSMetadataItemFSCreationDateKey] compare: [item1 valueForAttribute:NSMetadataItemFSCreationDateKey]];

}];

for (NSMetadataItem *item in results) {

NSURL *url = [item valueForAttribute:NSMetadataItemURLKey]; [self.documentURLs addObject:url];

[(NSMutableArray *)documentFilenames addObject:[url lastPathComponent]];

}

[self.tableView reloadData];

}

The query’s results contain a list of NSMetadataItem objects, from which we can get items like file URLs and creation dates. We use this to sort the items by date, and then grab all the URLs for later use.

Save Where?

The next change is to the urlForFilename: method, which once again is completely different. Here, we’re using a ubiquitous URL to create a full path URL for a given file name. We insert "Documents" in the generated path as well, to make sure we’re using the app’s Documents directory. Delete the old method, and replace it with this new one:

-(NSURL *)urlForFilename:(NSString *)filename {

//be sure to insert "Documents" into the path

www.it-ebooks.info

CHAPTER 14: Hey! You! Get onto iCloud!

521

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

NSURL *pathURL = [baseURL URLByAppendingPathComponent:@"Documents"]; NSURL *destinationURL = [pathURL URLByAppendingPathComponent:filename]; return destinationURL;

}

Now, build and run your app on an actual iOS device (not the simulator). If you’ve run the previous version of the app on that device, you’ll find that any TinyPix masterpieces you created earlier are now nowhere to be seen. This new version ignores the local Documents directory for the app, and relies completely on iCloud. However, you should be able to create new documents, and find that they stick around after quitting and restarting the app. Moreover, you can even delete the TinyPix app from your device entirely, run it again from Xcode, and find that all your iCloud-saved documents are available at once. If you have an additional iOS device configured with the same iCloud user, use Xcode to run the app on that device, and you’ll see all the same documents appear there as well! It’s pretty sweet.

Storing Preferences on iCloud

We can “cloudify” one more piece of functionality with just a bit of effort. iOS 5 includes a new class called NSUbiquitousKeyValueStore, which works a lot like an NSDictionary

(or NSUserDefaults, for that matter), but whose keys and values are stored in the cloud. This is great for application preferences, login tokens, and anything else that doesn’t belong in a document but could be useful when shared among all of a user’s devices.

In TinyPix, we’ll use this feature to store the user’s preferred highlight color. That way, instead of needing to be configured on each device, the user sets the color once, and it shows up everywhere.

Select BIDMasterViewController.m so we can make a couple of small changes. First, find chooseColor:, and make the following changes:

- (IBAction)chooseColor:(id)sender {

NSInteger selectedColorIndex = [(UISegmentedControl *)sender selectedSegmentIndex]; NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];

[prefs setInteger:selectedColorIndex forKey:@"selectedColorIndex"];

NSUbiquitousKeyValueStore *prefs = [NSUbiquitousKeyValueStore defaultStore]; [prefs setLongLong:selectedColorIndex forKey:@"selectedColorIndex"];

}

Here, we grab a slightly different object instead of NSUserDefaults. This new class doesn’t have a setInteger: method, so we use setLongLong: instead, which will do the same thing.

Then find the viewWillAppear: method, and change it as shown here:

- (void)viewWillAppear:(BOOL)animated

{

[super viewWillAppear:animated];

NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];

NSInteger selectedColorIndex = [prefs integerForKey:@"selectedColorIndex"];

www.it-ebooks.info

Соседние файлы в предмете [НЕСОРТИРОВАННОЕ]