1
#import <UIKit/UIKit.h>

@interface MyDocument : UIDocument

@property (strong) NSData *zipDataContent;
@property (nonatomic, assign) id delegate;
@end

#import "MyDocument.h"

@implementation MyDocument
@synthesize zipDataContent;
@synthesize delegate = _delegate;

- (BOOL)loadFromContents:(id)contents ofType:(NSString *)typeName
                   error:(NSError **)outError
{
    if ([contents length] > 0)
    {
        self.zipDataContent = [[NSData alloc] initWithBytes:[contents bytes] length:[contents length]];
        [[NSNotificationCenter defaultCenter] postNotificationName:@"noteModified" object:self];
        return YES;
    }
    else
    {
    }
    return YES;
}
- (id)contentsForType:(NSString *)typeName error:(NSError **)outError
{
    return self.zipDataContent;
}
@end
#import <UIKit/UIKit.h>
#import "MyDocument.h"
#import "ZipArchive.h"

@interface ViewController : UIViewController<UITextViewDelegate>
{
    NSMetadataQuery *_query;
}
@property (nonatomic,retain) IBOutlet UIButton * btnLoadDatabase;
@property (strong) NSMetadataQuery *_query;

-(IBAction) iCloudSyncing:(id)sender;
- (void)loadDocument ;
@end
#import "ViewController.h"
#define kFILENAME @"DiaryDB"

@interface ViewController ()

@end

@implementation ViewController
@synthesize btnLoadDatabase;
@synthesize _query;

-(void)dealloc
{
    [btnLoadDatabase release];
    [super dealloc];
}
- (void)viewDidLoad
{
    self.view.backgroundColor=[UIColor whiteColor];
    [super viewDidLoad];

}

-(BOOL)zipFolder:(NSString *)toCompress zipFilePath:(NSString *)zipFilePath
{
    BOOL isDir=NO;
       NSString *documentsDirectory = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
/    NSString *pathToCompress = [[NSBundle mainBundle] pathForResource:@"DiaryDB" ofType:@".sqlite"];


    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];
        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
{
    NSURL *ubiq = [[NSFileManager defaultManager]
                   URLForUbiquityContainerIdentifier:nil];
    if (ubiq)
    {
        NSLog(@"iCloud access at %@", ubiq);
               NSString *documentsDirectory = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];

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

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

        MyDocument *mydoc = [[MyDocument alloc] initWithFileURL:ubiquitousPackage];
        NSString *zipFilePath = [documentsDirectory stringByAppendingPathComponent:@"DiaryDB"];
        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");
                 [self loadDocument];
             }
             else
                 NSLog(@"PictureZip: Syncing FAILED with icloud");

         }];
    }
    else
    {
        NSLog(@"No iCloud access");
    }

}
- (void)loadDocument {

    NSMetadataQuery *query = [[NSMetadataQuery alloc] init];
    _query = query;

    [query setSearchScopes:[NSArray arrayWithObject:NSMetadataQueryUbiquitousDocumentsScope]];

    NSPredicate *pred = [NSPredicate predicateWithFormat: @"%K == %@", NSMetadataItemFSNameKey, kFILENAME];
    [query setPredicate:pred];

    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(queryDidFinishGathering:) name:NSMetadataQueryDidFinishGatheringNotification object:query];
    [query startQuery];


}
- (void)queryDidFinishGathering:(NSNotification *)notification {

    NSMetadataQuery *query2 = [notification object];
    [query2 disableUpdates];
    [query2 stopQuery];

    [[NSNotificationCenter defaultCenter] removeObserver:self
                                                    name:NSMetadataQueryDidFinishGatheringNotification
                                                  object:query2];
    [self loadData:query2];

}
- (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:@"DiaryDB"])
        {
            [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:@"DiaryDB.zip"];
                    [[NSFileManager defaultManager] createFileAtPath:zipFolder contents:file attributes:nil];
                    NSString *outputFolder = [documentsDirectory stringByAppendingPathComponent:@"DiaryDB"];//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);
                    }
                    for (NSString *file in files)
                    {
                        NSLog(@" Pictures %@",file);
                    }

                }
                else
                {
                    NSLog(@"Pictures : failed to open from iCloud");
                                   }
            }]; 
        }
    }
}
- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
}

@end

*这是我用来制作 zip 到 sqlite 数据库并将 zip 同步到 iCloud 以及从 iCloud 中检索数据库的 zip 的代码,它无法通过此代码正常工作我无法从数据库访问 zip 文件,我还想在 mainbundell 上保存 zip 文件 *

4

0 回答 0