iOS 文件/文件夹 压缩封装方法

本文介绍了如何在iOS中使用ZipArchive库进行文件和文件夹的压缩操作。通过导入libz.dylib库,实现将指定路径的文件或文件夹压缩成ZIP文件,并提供了详细的代码示例。

基于ZipArchive.zip  导入libz.dylib库


/**

 *  根据路径将文件压缩为zip到指定路径

 *

 *  @param sourcePath 压缩文件夹路径

 *  @param destZipFile存放路径(保存重命名)

 */

+(void) doZipAtPath:(NSString*)sourcePath to:(NSString*)destZipFile 

{

    NSFileManager *fileManager = [NSFileManager defaultManager];

    ZipArchive * zipArchive = [ZipArchive new];

    BOOL isdic;

    //判断sourcePath下是文件夹还是文件

    if(![fileManager fileExistsAtPath:sourcePath isDirectory:&isdic])

        return;//文件已存在,直接返回

    

    [zipArchive CreateZipFile2:destZipFile];

    

    if (isdic)//文件夹

    {

        NSArray *fileList = [fileManager contentsOfDirectoryAtPath:sourcePath error:nil];//文件列表

        for(NSString *filePath in fileList){

            NSString *fileName = [filePath lastPathComponent];//取得文件名

            NSString *path = [sourcePath stringByAppendingString:[NSString stringWithFormat:@"/%@",filePath]];

            [zipArchive addFileToZip:path newname:fileName];

        }

    }

    else

    {

        [zipArchive addFileToZip:sourcePath newname:[sourcePath lastPathComponent]];

    }

    

    [zipArchive CloseZipFile2];

}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值