【问题标题】:Zip file not created properly in iOS在 iOS 中未正确创建 Zip 文件
【发布时间】:2016-07-12 08:39:35
【问题描述】:

我正在将所有 NSLOG 写入一个文本文件,并通过单击 table view cell 将其发布到服务器。在使用 NSURLConnection 发布之前,我将文本文件转换为 zip 文件。但是,发布的 Zip 文件中存在一些垃圾数据,但文本文件的内容正确。我正在使用 SSZipArchive,我用来发布文件的代码是

 NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *logFilePath = [documentsDirectory stringByAppendingPathComponent:[NSString stringWithFormat:@"Logger.txt"]];

NSString* zipfile = [documentsDirectory stringByAppendingPathComponent:[NSString stringWithFormat:@"Logger.zip"]];
//create zip file, return true on success

BOOL isZipCreated=[SSZipArchive createZipFileAtPath:zipfile withContentsOfDirectory:logFilePath];

if (isZipCreated) {

    NSLog(@"Zip file Created at Path : %@",zipfile);
     NSString *contentOfZipFile = [NSString stringWithContentsOfFile:zipfile encoding:NSUTF8StringEncoding error:NULL];
    NSData *zipData = [contentOfZipFile dataUsingEncoding:NSUTF8StringEncoding];


    NSString *postLength = [NSString stringWithFormat:@"%lu", (unsigned long)[zipData length]];

    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:finalURL]];
    [request setHTTPMethod:@"POST"];
    [request setValue:postLength forHTTPHeaderField:@"Content-Length"];
    [request setValue:@"application/zip" forHTTPHeaderField:@"Content-Type"];
    [request setHTTPBody:zipData ];


    NSURLConnection *conn = [[NSURLConnection alloc]initWithRequest:request delegate:self];
}

else {
     NSLog(@"Zip create error");
}

任何帮助都会有很大帮助。

【问题讨论】:

    标签: ios objective-c zip


    【解决方案1】:

    你可以使用这个库Objective-Zip,实际上我已经使用了它并且它对我来说工作正常。

    创建 Zip 文件:

    ZipFile *zipFile= [[ZipFile alloc] initWithFileName:@"Logger.zip" mode:ZipFileModeCreate];
    

    将文件添加到 zip 文件中

    ZipWriteStream *stream= [zipFile writeFileInZipWithName:@"Logger.txt" compressionLevel:ZipCompressionLevelBest];
    

    [流写入数据:abcData]; [流完成写作];

    从 zip 文件中读取文件:

    ZipFile *unzipFile= [[ZipFile alloc] initWithFileName:@"Logger.zip" mode:ZipFileModeUnzip];
    
    [unzipFile goToFirstFileInZip];
    
    ZipReadStream *read= [unzipFile readCurrentFileInZip];
    NSMutableData *data= [[NSMutableData alloc] initWithLength:256];
    int bytesRead= [read readDataWithBuffer:data];
    
    [read finishedReading];
    

    希望此代码对您有所帮助 :) 编码快乐!! ;)

    【讨论】:

    • 你能解释一下我需要做什么来安装这个库吗?
    • 您可以在项目中添加 pod,并按照他们在 github 链接上解释的步骤进行操作。 github.com/gianlucabertani/Objective-Zip
    • 压缩文件在哪里创建?
    • 您可以签入文件夹。 NSString *documentsDir= [NSHomeDirectory() stringByAppendingPathComponent:@"Documents"]; NSString *filePath= [documentsDir stringByAppendingPathComponent:@"Logger.zip"];
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-02-26
    • 2019-05-20
    • 2018-10-21
    • 1970-01-01
    • 2015-01-11
    • 1970-01-01
    相关资源
    最近更新 更多