Как я могу использовать iCloud для синхронизации .zip файла между моими приложениями? - PullRequest
6 голосов
/ 08 ноября 2011

Можно ли загрузить файл .zip в iCloud, а затем синхронизировать его на всех устройствах iOS пользователя?
Если так, как бы я поступил так?
Если есть ограничение на размер файла, также укажите макс. допустимый размер файла.

Ответы [ 3 ]

18 голосов
/ 09 апреля 2012

Так я синхронизировал zip-файлы с iCloud.

Шаги:

1) http://transoceanic.blogspot.in/2011/07/compressuncompress-files-on.html , Перейдите по этой ссылке, чтобы скачать zip api с кодом для архивирования и распаковки папки.

2) Теперь все, что вам нужно для игры с NSData.

3) Файл "MyDocument.h"

#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) Теперь где-то в вашем приложении вам нужно сжать папку и синхронизировать с 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) Вы можете разархивировать данные, полученные из iCloud, следующим образом.

- (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];
                }
            }]; 
        }
}
}
2 голосов
/ 20 декабря 2011

Возможно, этот урок поможет вам больше:

http://www.raywenderlich.com/6015/beginning-icloud-in-ios-5-tutorial-part-1

2 голосов
/ 13 декабря 2011

Чтобы включить хранение документов в iCloud , ваш «документ» должен быть инкапсулирован в UIDocument объект.

Поскольку UIDocument ссылается на URL файла, вы можете легко создать UIDocument, указывающий на file://myzipfile.zip, а затем загрузить zip-документ в iCloud .

Надеюсь, это поможет

...