Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can i save NSData in iCloud

I have NSData in my App and i want to save that data in iCloud. I DONT want to synchronize my NSUserDefaults with iCloud, so its no clone of "Can I use iCloud to sync the NSUserDefaults plist file". Is that possible? How can i do that? How can I retrieve that saved data?

like image 674
Wed Avatar asked Dec 30 '25 18:12

Wed


2 Answers

Yes it is possible. I have done that before and my answer is at syncing zip with iCloud,in which I am creating zip and converting it into NSData and syncing with iCloud, later I am receiving NSData and again converting back it into zip and unzipping content. Here your main need is syncing of NSData so All you to have work around for NSData.

1) Create subclass of 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) Syncing with iCloud (You can do as per you need)

-(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");

     }];
}

Hope this helps..

like image 171
βhargavḯ Avatar answered Jan 01 '26 09:01

βhargavḯ


// 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 :)
like image 34
Rein rPavi Avatar answered Jan 01 '26 11:01

Rein rPavi



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!