Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I use iCloud to synchronize a .zip file between my apps?

Is it possible to upload a .zip file to iCloud, and then have it be synchronized across all of a user's iOS devices?
If so, how would I go about doing this?
If there is any File size limit, then also mention max. file size allowed.

like image 352
Mobile App Dev Avatar asked Nov 08 '11 07:11

Mobile App Dev


People also ask

How do I upload a ZIP file to iCloud?

Upload filesDrag files from the desktop or a folder window on your computer to the iCloud Drive window or a folder icon in the iCloud Drive window. If you drag to a folder icon, it becomes highlighted to confirm that the item you're dragging will go into the folder.

Can you sync apps to iCloud?

Open the Settings app on one device, tap your name to open the Apple ID screen, then select iCloud. Turn on the toggle switches next to every category of app and content that you want to sync between the iPhone and iPad.

Can you link to files in iCloud?

This iCloud URL – something like https://www.icloud.com/iclouddrive/0gfR5JXx_XnSXcxyfuQKTtYDw#Ulysses_automation – can act as a deep link into the Files app to that file directly, which you can use elsewhere as a quick way to jump to that file at a moment's notice.


2 Answers

This is how I synchronized zip files with iCloud .

Steps:

1) http://transoceanic.blogspot.in/2011/07/compressuncompress-files-on.html . Refer this link to download zip api which is having code for zipping and unzipping folder.

2) Now all you need to play with NSData.

3) "MyDocument.h" file

#import <UIKit/UIKit.h>

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

4)

#import "MyDocument.h"

@implementation MyDocument
@synthesize zipDataContent;

// Called whenever the application reads data from the file system
- (BOOL)loadFromContents:(id)contents ofType:(NSString *)typeName error:(NSError **)outError
{
    self.zipDataContent = [[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.zipDataContent;
}

@end

5) Now somewhere in your app you need to zip folder and sync with icloud.

-(BOOL)zipFolder:(NSString *)toCompress zipFilePath:(NSString *)zipFilePath
{
    BOOL isDir=NO;

    NSString *documentsDirectory = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
    NSString *pathToCompress = [documentsDirectory stringByAppendingPathComponent:toCompress];

    NSArray *subpaths;
    NSFileManager *fileManager = [NSFileManager defaultManager]; 
    if ([fileManager fileExistsAtPath:pathToCompress isDirectory:&isDir] && isDir){
        subpaths = [fileManager subpathsAtPath:pathToCompress];
    } else if ([fileManager fileExistsAtPath:pathToCompress]) {
        subpaths = [NSArray arrayWithObject:pathToCompress];
    }

    zipFilePath = [documentsDirectory stringByAppendingPathComponent:zipFilePath];
    //NSLog(@"%@",zipFilePath);
    ZipArchive *za = [[ZipArchive alloc] init];
    [za CreateZipFile2:zipFilePath];
    if (isDir) {
        for(NSString *path in subpaths){  
            NSString *fullPath = [pathToCompress stringByAppendingPathComponent:path];
            if([fileManager fileExistsAtPath:fullPath isDirectory:&isDir] && !isDir){
                [za addFileToZip:fullPath newname:path];  
            }
        }
    } else {
        [za addFileToZip:pathToCompress newname:toCompress];
    }

    BOOL successCompressing = [za CloseZipFile2];
    if(successCompressing)
        return YES;
    else
        return NO;
}
-(IBAction) iCloudSyncing:(id)sender  
{
    //***** PARSE ZIP FILE : Pictures *****
    NSString *documentsDirectory = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];

    if([self zipFolder:@"Pictures" zipFilePath:@"iCloudPictures"])
        NSLog(@"Picture Folder is zipped");

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

    mydoc = [[MyDocument alloc] initWithFileURL:ubiquitousPackage];
    NSString *zipFilePath = [documentsDirectory stringByAppendingPathComponent:@"iCloudPictures"];
    NSURL *u = [[NSURL alloc] initFileURLWithPath:zipFilePath];
    NSData *data = [[NSData alloc] initWithContentsOfURL:u];
    // NSLog(@"%@ %@",zipFilePath,data);
    mydoc.zipDataContent = data;

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

    }];
}

6) You can unzip data received from iCloud like this.

- (void)loadData:(NSMetadataQuery *)queryData {



    for (NSMetadataItem *item in [queryData results]) 
    {    
        NSString *filename = [item valueForAttribute:NSMetadataItemDisplayNameKey];


        NSURL *url = [item valueForAttribute:NSMetadataItemURLKey];
        MyDocument *doc = [[MyDocument alloc] initWithFileURL:url];

if([filename isEqualToString:@"iCloudPictures"])
        {
            [doc openWithCompletionHandler:^(BOOL success) {
                if (success) {
                    NSLog(@"Pictures : Success to open from iCloud");
                    NSData *file = [NSData dataWithContentsOfURL:url];

                    NSString *documentsDirectory = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
                    NSString *zipFolder = [documentsDirectory stringByAppendingPathComponent:@"Pics.zip"];
                    [[NSFileManager defaultManager] createFileAtPath:zipFolder contents:file attributes:nil];
                    //NSLog(@"zipFilePath : %@",zipFolder);

                    NSString *outputFolder = [documentsDirectory stringByAppendingPathComponent:@"Pictures"];//iCloudPics
                    ZipArchive* za = [[ZipArchive alloc] init];
                    if( [za UnzipOpenFile: zipFolder] ) {
                        if( [za UnzipFileTo:outputFolder overWrite:YES] != NO ) {
                            NSLog(@"Pics : unzip successfully");
                          }
                        [za UnzipCloseFile];
                    }
                    [za release];


                    NSError *err;
                    NSArray *files = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:outputFolder error:&err];
                    if (files == nil) {
                        NSLog(@"EMPTY Folder: %@",outputFolder);
                    }
                    // Add all sbzs to a list    
                    for (NSString *file in files) {
                        //if ([file.pathExtension compare:@".jpeg" options:NSCaseInsensitiveSearch] == NSOrderedSame) {        
                        NSLog(@" Pictures %@",file);

                        //                            NSFileManager *fm = [NSFileManager defaultManager];
                        //                            NSDictionary *attributes = [fm fileAttributesAtPath:[NSString stringWithFormat:@"%@/%@",documentsDirectory,file]                                                                 traverseLink:NO];
                        //                            
                        //                            NSNumber* fileSize = [attributes objectForKey:NSFileSize];
                        //                            int e = [fileSize intValue]; //Size in bytes
                        //                            NSLog(@"%@__%d",file,e);           
                    }

                }
                else 
                {
                    NSLog(@"Pictures : failed to open from iCloud");
                    [self hideProcessingView];
                }
            }]; 
        }
}
}
like image 124
βhargavḯ Avatar answered Oct 21 '22 18:10

βhargavḯ


In order to enabling Document storage in iCloud your "document" needs to be encapsulated in a UIDocument object.

Because UIDocument links to a file URL, you can easily create a UIDocument pointing to file://myzipfile.zip and then upload a zip document to iCloud.

I hope this helps

like image 29
iGranDav Avatar answered Oct 21 '22 16:10

iGranDav