iCloud

icloud

  • The Application Stores Directory, also known as the application sandbox, is a
    local directory that currently holds the original Grocery-Dude.sqlite store. An iCloud.sqlite store will be added to this folder in a subfolder specific to each iCloud user. The per-user subfolders are managed transparently by Core Data. The folder structure is shown at the end of the chapter in the “Exercises” section.
  • The Ubiquity Container is where iCloud documents and data specific to the authenticated iCloud user are found. Everything in this folder is synchronized automatically with the iCloud servers. If a directory with a .nosync suffix is stored
    in the ubiquity container, its contents will not be synchronized. You may have seen implementations of iCloud where the iCloud Store was placed in a .nosync folder of the ubiquity container. This approach is no longer recommended since iOS 7 because it prevents Core Data from transparently managing a Fallback Store. A Fallback Store is used to provide seamless transitions between iCloud accounts and reduce the time it takes for the iCloud Store to become usable for the first time. The Fallback Store is also used when the user is logged out of iCloud, or has disabled iCloud Documents & Data.
  • iCloud is the name of the service allowing a user’s data to be synchronized across all
    of his or her devices. It is possible to see the contents of your iCloud container for debugging purposes at https://developer.icloud.com. You can also perform metadata queries to inspect the contents of iCloud or use the iCloud Debug Navigator introduced in Xcode 5, which will be shown later in the chapter. Each application using iCloud has its own directory at the root of iCloud, and applications from the same developer can be configured to share a ubiquity container within it. This is useful if you need to maintain separate free and paid versions of an application that need to access the same data.

Create file to iCloud
Icloud’s local path from phone: file:///private/var/mobile/Library/Mobile%20Documents/TeamID~com~toogoogoo~iCloud/

iCloud’s local path from simulator: file:///Users/xushao/Library/Application%20Support/iPhone%20Simulator/7.0.3/Library/Mobile%20Documents/TeamID ~com~toogoogoo~Test/

如果在该目录手动创建文件,icloud也会同步创建

NSURL * iCloudURL = [self.fManager URLForUbiquityContainerIdentifier:nil];这个url的目录为:根目录

//
//  iCloudAppDelegate.m
//  iCloud
//
//  Created by xushao on 2/24/14.
//  Copyright (c) 2014 TGG. All rights reserved.
//

#import "iCloudAppDelegate.h"

@interface iCloudAppDelegate ()
@property(nonatomic, strong)NSFileManager *fManager;
@property(nonatomic, strong)NSMetadataQuery *iCloudQuery;

@end

@implementation iCloudAppDelegate

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
    // Override point for customization after application launch.
    /*
    NSString *stringValuekey2 = @"My String";
    NSString *stringValueKey = @"MyStringKey";
    NSUbiquitousKeyValueStore *KVStore =  [[NSUbiquitousKeyValueStore alloc] init];
    
    if ([[KVStore stringForKey:stringValuekey2] length]==0) {
        [self alert:@"no string, settting"];
        [KVStore setString:@"this is string" forKey:stringValueKey];
        [KVStore setString:@"stringValuekey2" forKey:stringValuekey2];
    }else{
        [self alert:[NSString stringWithFormat:@"Result is :%@ and %@",[KVStore stringForKey:stringValueKey],[KVStore stringForKey:stringValuekey2]]];
    }
    
    
    
    
    if (![fManager fileExistsAtPath:[[self documentURL] path]]) {
        
        [self alert:[NSString stringWithFormat:@"createDirectoryAtPath %@ ", [self documentURL]]];
        [fManager createDirectoryAtPath:[[self documentURL] path] withIntermediateDirectories:YES attributes:nil error:nil];
    }else{
        [self alert:@"File already exit"];
    }
     

    if (![self.fManager fileExistsAtPath:[[self documentURL] path]]) {
        
        [self alert:[NSString stringWithFormat:@"createDirectoryAtURL %@ ", [self documentURL]]];
        
        [self.fManager createDirectoryAtURL:[self documentURL] withIntermediateDirectories:YES
                                 attributes:nil error:nil  ];
        //[self.fManager createDirectoryAtPath:[[self documentURL] path] withIntermediateDirectories:YES attributes:nil error:nil];
    }else{
        [self alert:@"File already exit"];
    }
     */
    self.fManager = [NSFileManager defaultManager];
   NSString * TeamID = @"FUHS6YZAHW";
    NSString *buddleIdentifier = [[NSBundle mainBundle] bundleIdentifier];
    NSString *identifier = [NSString stringWithFormat:@"%@.%@", TeamID, buddleIdentifier];
    
    
   NSURL * iCloudURL = [self.fManager URLForUbiquityContainerIdentifier:nil];
    NSError *error = nil;
   // NSString *documentDirec = [[iCloudURL path] stringByAppendingPathComponent:@"Documents"];
    NSURL *documentURL = [iCloudURL URLByAppendingPathComponent:@"Documents" isDirectory:YES];
    //NSString *createDocument = [documentDirec stringByAppendingPathComponent:@"David"];
    if (![self.fManager fileExistsAtPath:[documentURL path]]) {
        
        
        [self.fManager createDirectoryAtPath:[documentURL path] withIntermediateDirectories:YES attributes:nil error:&error];
        if (!error) {
            [self alert:[NSString stringWithFormat:@"create iCloudURL: %@ ", iCloudURL]];
            NSLog(@"%@",iCloudURL);
        }else{
            NSLog(@"error1");
        }
        
    }else{
        
        NSString *textString = @"This is text";
        NSURL *FileURL = [documentURL URLByAppendingPathComponent:@"latest.text"];
       // NSString *path = [documentURL stringByAppendingPathComponent:@"JacobString.sql"];
        NSError *error = nil;
        if ([textString writeToURL:FileURL atomically:YES encoding:NSUTF8StringEncoding error:&error]) {
            if (!error) {
                //NSData *data = [self.fManager contentsAtPath:path];
                //NSString *string = [NSString stringWithContentsOfFile:path encoding:NSUTF8StringEncoding error:&error];
                //[self alert:[NSString stringWithFormat:@"The content is : %@", string]];
            }else{
                 NSLog(@"error2");
            }
        }else{
            [self alert:@"Couldn't write to"];
        }
    }
    
    
    //
    NSURL *fileURL = [[self documentURL] URLByAppendingPathComponent:@"JacobLocal.String.txt"];
    if ([self.fManager fileExistsAtPath:[fileURL path]]) {
        if ([self.fManager setUbiquitous:YES itemAtURL:fileURL destinationURL:documentURL error:&error]) {
            if (!error) {
                NSLog(@"successful upload");
            }else{
                NSLog(@"error3");
            }
        }else{
            NSLog(@"couldn't");
        }
        
    }
    
    if ([self.iCloudQuery startQuery]) {
        [self alert:@"start query"];
    }else{
        NSLog(@"not query");
    }
    
    
    return YES;
    
}

-(NSMetadataQuery *)iCloudQuery
{
    if (!_iCloudQuery) {
        _iCloudQuery = [[NSMetadataQuery alloc] init];
        _iCloudQuery.searchScopes = [NSArray arrayWithObject:NSMetadataQueryUbiquitousDocumentsScope];
        _iCloudQuery.predicate = [NSPredicate predicateWithFormat:@"%K LIKE '*'",NSMetadataItemFSNameKey];
        
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(preocessQueryResult:) name:NSMetadataQueryDidFinishGatheringNotification object:_iCloudQuery];
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(preocessQueryResult:) name:NSMetadataQueryDidUpdateNotification object:_iCloudQuery];
    
    }
    
    return _iCloudQuery;
}

-(void)preocessQueryResult:(NSNotification *)notification{
    [self.iCloudQuery disableUpdates];
    NSMutableArray *UrlArray = [[NSMutableArray alloc] init];
    NSUInteger resultIndex = [self.iCloudQuery resultCount];
    NSLog(@"resultIndex is %d",resultIndex);

    for (int i = 0; i < resultIndex; i++) {
        NSMetadataItem *item = [self.iCloudQuery resultAtIndex:i];
        NSURL *url = [item valueForAttribute:NSMetadataItemURLKey];

        [UrlArray addObject:[url pathComponents]];
    }
    
    [self.iCloudQuery enableUpdates];
}

-(NSURL *)documentURL{
    NSURL *documentDirectory = [[[NSFileManager defaultManager] URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask] lastObject];
    return [documentDirectory URLByAppendingPathComponent:@"TGGDocument"];
}

-(void)alert:(NSString *)msg{
    
    [[[UIAlertView alloc] initWithTitle:@"Noticed" message:msg delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil, nil] show];
}
	

DocumentTVC

//
// DocumentTVC.m
// Test
//
// Created by xushao on 2/23/14.
// Copyright (c) 2014 TGG. All rights reserved.
//

#import "DocumentTVC.h"

@interface DocumentTVC ()
@property(nonatomic, strong)NSArray *documents;
@property(nonatomic, strong)NSMetadataQuery *icloudQuery;
@end

@implementation DocumentTVC

-(void)viewDidLoad
{
if (DEBUG == 1) {
NSLog(@"%@ is %@",self.class, NSStringFromSelector(_cmd));
}
[super viewDidLoad];
NSLog(@"%@", [self iCloudURL]);
}
-(NSURL *)iCloudURL{
return [[NSFileManager defaultManager] URLForUbiquityContainerIdentifier:nil];
}

@synthesize documents = _documents;

-(void)setDocuments:(NSArray *)documents
{
_documents = documents;
[self.tableView reloadData];
}

-(void)processIcloudqueryResult:(NSNotification *)notificatin{
[self.icloudQuery disableUpdates];

NSUInteger resultCount = [self.icloudQuery resultCount];

for (int i = 0; i < resultCount; i ++) { NSMetadataItem *item = [self.icloudQuery resultAtIndex:i]; NSURL *url = [item valueForAttribute:NSMetadataItemURLKey]; } } /* [item valueForAttribute:NSMetadataItemURLKey]; NSString * const NSMetadataItemFSNameKey; NSString * const NSMetadataItemDisplayNameKey; NSString * const NSMetadataItemURLKey; NSString * const NSMetadataItemPathKey; NSString * const NSMetadataItemFSSizeKey; NSString * const NSMetadataItemFSCreationDateKey; NSString * const NSMetadataItemFSContentChangeDateKey; */ -(NSMetadataQuery *)icloudQuery { if (!_icloudQuery) { _icloudQuery = [[NSMetadataQuery alloc] init]; _icloudQuery.searchScopes = [NSArray arrayWithObject:NSMetadataQueryUbiquitousDocumentsScope]; //NSString * const NSMetadataQueryUbiquitousDocumentsScope; // NSString * const NSMetadataQueryUbiquitousDataScope; _icloudQuery.predicate = [NSPredicate predicateWithFormat:@"%K like '*'",NSMetadataItemFSNameKey ]; [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(processIcloudqueryResult:) name:NSMetadataQueryDidFinishGatheringNotification object:_icloudQuery]; [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(processIcloudqueryResult:) name:NSMetadataQueryDidUpdateNotification object:_icloudQuery]; } return _icloudQuery; } -(void)viewWillAppear:(BOOL)animated { [super viewWillAppear:animated]; if (![self.icloudQuery isStarted]) { [self.icloudQuery enableUpdates]; } } -(void)viewWillDisappear:(BOOL)animated { [super viewWillDisappear:animated]; [self.icloudQuery disableUpdates]; } #pragma mark - Table view data source - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section { // Return the number of rows in the section. return [self.documents count]; } - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { static NSString *CellIdentifier = @"Document Cell"; UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath]; // Configure the cell... cell.textLabel.text = [[self.documents objectAtIndex:indexPath.row] lastPathComponent]; return cell; } /* // Override to support conditional editing of the table view. - (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath { // Return NO if you do not want the specified item to be editable. return YES; } */ /* // Override to support editing the table view. - (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath { if (editingStyle == UITableViewCellEditingStyleDelete) { // Delete the row from the data source [tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade]; } else if (editingStyle == UITableViewCellEditingStyleInsert) { // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view } } */ /* // Override to support rearranging the table view. - (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath { } */ /* // Override to support conditional rearranging of the table view. - (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath { // Return NO if you do not want the item to be re-orderable. return YES; } */ /* #pragma mark - Navigation // In a story board-based application, you will often want to do a little preparation before navigation - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender { // Get the new view controller using [segue destinationViewController]. // Pass the selected object to the new view controller. } */ @end