Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
309 views
in Technique[技术] by (71.8m points)

iphone - 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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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];
                }
            }]; 
        }
}
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...