iOS - 压缩与解压缩

-(void)zip{
   NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *docspath = [paths objectAtIndex:0];
    NSString *eawPath = [[NSBundle mainBundle] pathForResource:@"ClientRes" ofType:@"zip"];
    NSLog(@"eawPath ===%@ ",eawPath);
    NSString *eawRPath = [docspath stringByAppendingPathComponent:@"ClientRes.zip"];
    dispatch_queue_t q = dispatch_queue_create("cn.itcast.gcddemo",DISPATCH_QUEUE_CONCURRENT);
    // 拷贝压缩包到沙盒
    dispatch_sync(q, ^{
        [[NSFileManager defaultManager] copyItemAtPath:eawPath toPath:eawRPath error:NULL];
    });
    // 解压压缩包
    dispatch_sync(q, ^{
        [self OpenZip:eawRPath unzipto:docspath];
    });
    // 删除压缩包
    dispatch_sync(q, ^{
        [self deletDocumentsFile:eawRPath];
    });
    PostToUnityOne(StartGame, nil);
}

// 解压zip包

- (void)OpenZip:(NSString*)zipPath unzipto:(NSString*)_unzipto
{
BOOL blHave=[[NSFileManager defaultManager] fileExistsAtPath:zipPath];
    if (!blHave) {
        NSLog(@"no  have");
        return ;
    }else {
        ZipArchive* zip = [[ZipArchive alloc] init];
        if( [zip UnzipOpenFile:zipPath] )
        {
            BOOL ret = [zip UnzipFileTo:_unzipto overWrite:YES];
            if( NO==ret )
            {
                NSLog(@"error");
            }
            [zip UnzipCloseFile];
        }
    }
}

// 删除沙盒文件

-(void)deletDocumentsFile:(NSString *)filePath{
    //文件名
    BOOL blHave=[[NSFileManager defaultManager] fileExistsAtPath:filePath];
    if (!blHave) {
        NSLog(@"no  have");
        return ;
    }else {
        NSLog(@" have");
        BOOL blDele= [[NSFileManager defaultManager] removeItemAtPath:filePath error:nil];
        if (blDele) {
            NSLog(@"dele success");
        }else {
            NSLog(@"dele fail");
        }
    }
}

// 删除缓存

-(void)deleteCaches{
    // 删除缓存
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);
    NSString *cachesDir = [paths objectAtIndex:0];
    NSArray *files = [[NSFileManager defaultManager] subpathsAtPath: cachesDir];
    [files enumerateObjectsUsingBlock:^(NSString   * obj, NSUInteger idx, BOOL * _Nonnull stop) {
        NSString *pathS=[cachesDir stringByAppendingPathComponent:obj];
        [self deletDocumentsFile:pathS];
    }]
}

ZipArchive库:https://pan.baidu.com/s/1bpaSFPt

你可能感兴趣的:(iOS - 压缩与解压缩)