簡體   English   中英

如何在iCloud中保存NSData

[英]How can i save NSData in iCloud

我在我的應用程序中有NSData,我想在iCloud中保存這些數據。 我不想將我的NSUserDefaults與iCloud同步,所以它沒有克隆“ 我可以使用iCloud來同步NSUserDefaults plist文件 ”。 那可能嗎? 我怎樣才能做到這一點? 如何檢索保存的數據?

對的,這是可能的。 之前我已經完成了這個,我的答案是在與iCloud同步zip ,我正在創建zip並將其轉換為NSData並與iCloud同步,之后我收到NSData並再次將其轉換為zip和解壓縮內容。 這里你的主要需求是同步NSData,所以你要解決NSData

1)創建UIDocument子類

#import <UIKit/UIKit.h>

@interface MyDocument : UIDocument
    @property (strong) NSData *dataContent;
@end

2)MyDocument.m

#import "MyDocument.h"

@implementation MyDocument
@synthesize dataContent;

// Called whenever the application reads data from the file system
- (BOOL)loadFromContents:(id)contents ofType:(NSString *)typeName error:(NSError **)outError
{
    self.dataContent = [[NSData alloc] initWithBytes:[contents bytes] length:[contents length]];
    [[NSNotificationCenter defaultCenter] postNotificationName:@"noteModified" object:self];
    return YES;     
}

// Called whenever the application (auto)saves the content of a note
- (id)contentsForType:(NSString *)typeName error:(NSError **)outError 
{
    return self.dataContent;
}

@end

3)與iCloud同步(您可以根據需要進行)

-(IBAction) iCloudSyncing:(id)sender
{

    NSURL* ubiq = [[NSFileManager defaultManager]URLForUbiquityContainerIdentifier:nil];
    NSURL *ubiquitousPackage = [[ubiq URLByAppendingPathComponent:@"Documents"]  URLByAppendingPathComponent:@"iCloudPictures.zip"];

    MyDocument *mydoc = [[MyDocument alloc] initWithFileURL:ubiquitousPackage];
    NSData *data = << YOUR NSDATA >>;
    mydoc.dataContent = data;

    [mydoc saveToURL:[mydoc fileURL] forSaveOperation:UIDocumentSaveForCreating completionHandler:^(BOOL success)
     {
         if (success)
         {
             NSLog(@"Synced with icloud");
         }
         else
             NSLog(@"Syncing FAILED with icloud");

     }];
}

希望這可以幫助..

// 1. Any file can be uploaded to iCloud container of any size (yes you should be having that much of space in iCloud) lets take an example SampleData.zip

    // 2. This method will upload or sync SampleData.zip file in iCloud container, iCloud actually checks the metadata of your file before it uploads it into your iCloud container (so for first time it will upload the file and from next time it will only upload the changes)

    -(void) iCloudSyncing:(id)sender
    {
        //Doc dir
        NSString *documentsDirectory = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
        NSString *filePath = [documentsDirectory stringByAppendingPathComponent:@"SampleData.zip"];
        NSURL *u = [[NSURL alloc] initFileURLWithPath:filePath];
        NSData *data = [[NSData alloc] initWithContentsOfURL:u];

        //Get iCloud container URL
        NSURL *ubiq = [[NSFileManager defaultManager]URLForUbiquityContainerIdentifier:nil];// in place of nil you can add your container name
        //Create Document dir in iCloud container and upload/sync SampleData.zip
        NSURL *ubiquitousPackage = [[ubiq URLByAppendingPathComponent:@"Documents"]URLByAppendingPathComponent:@"SampleData.zip"];
        Mydoc = [[MyDocument alloc] initWithFileURL:ubiquitousPackage];
        Mydoc.zipDataContent = data;

        [Mydoc saveToURL:[Mydoc fileURL] forSaveOperation:UIDocumentSaveForCreating completionHandler:^(BOOL success)
         {
             if (success)
             {
                 NSLog(@"SampleData.zip: Synced with icloud");
             }
             else
                 NSLog(@"SampleData.zip: Syncing FAILED with icloud");

         }];
    }



      // 3 Download data from the iCloud Container

    - (IBAction)GetData:(id)sender {

        //--------------------------Get data back from iCloud -----------------------------//
        id token = [[NSFileManager defaultManager] ubiquityIdentityToken];
        if (token == nil)
        {
            NSLog(@"ICloud Is not LogIn");
        }
        else
        {
            NSLog(@"ICloud Is LogIn");

            NSError *error = nil;
            NSURL *ubiq = [[NSFileManager defaultManager]URLForUbiquityContainerIdentifier:nil];// in place of nil you can add your container name
            NSURL *ubiquitousPackage = [[ubiq URLByAppendingPathComponent:@"Documents"]URLByAppendingPathComponent:@"SampleData.zip"];
            BOOL isFileDounloaded = [[NSFileManager defaultManager]startDownloadingUbiquitousItemAtURL:ubiquitousPackage error:&error];
            if (isFileDounloaded) {
                NSLog(@"%d",isFileDounloaded);
                NSString *documentsDirectory = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
                //changing the file name as SampleData.zip is already present in doc directory which we have used for upload
                NSString* fileName = [NSString stringWithFormat:@"RecSampleData.zip"];
                NSString* fileAtPath = [documentsDirectory stringByAppendingPathComponent:fileName];
                NSData *dataFile = [NSData dataWithContentsOfURL:ubiquitousPackage];
                BOOL fileStatus = [dataFile writeToFile:fileAtPath atomically:NO];
                if (fileStatus) {
                    NSLog(@"success");
                }
            }
            else{
                NSLog(@"%d",isFileDounloaded);
            }
        }
    }

    //4 voila its done :)

1) 將數據轉換為zip文件,然后保存到icloud

2) 將xml文件保存到icloud

在這里你有解決方案來保存icloud中的數據,否則我們可以將這些數據寫入文件,我們可以通過提供文件路徑將該文件直接保存到icloud

對於自定義對象注意:限制為每個iCloud用戶1 MB!

+(void)write{

//Decode using
NSData *data = [NSKeyedArchiver archivedDataWithRootObject:[HistoryFile files]];

//Save Data To NSUserDefault
NSUbiquitousKeyValueStore *iCloud =  [NSUbiquitousKeyValueStore defaultStore];

//let ios know we want to save the data    
[iCloud setObject:data forKey:@"app_data"];


//iOS will save the data when it is ready.
[iCloud synchronize];

}


+(NSMutableArray*)read{
    //Read Settings Value From NSUserDefault
    //get the NSUserDefaults object

    NSUbiquitousKeyValueStore *iCloud =  [NSUbiquitousKeyValueStore defaultStore];
    //read value back from the settings
    NSData *data = [iCloud objectForKey:@"app_data"];
    NSMutableArray *data_array = (NSMutableArray*)[NSKeyedUnarchiver unarchiveObjectWithData:data];    
    NSLog(@"data_array %@",data_array);
    return data_array;
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM