AnxiousMan
AnxiousMan

Reputation: 588

Zip file not created properly in iOS

I am writing all the NSLOG's to a text file and post it to the server on click of a table view cell . I convert the text file to zip file before I post it using NSURLConnection . However , There is Some garbage data present inside the Zip file posted , But the text file has the correct content. I am using SSZipArchive, The code that I use to post the file is

 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");
}

Any assistance would be of great help.

Upvotes: 0

Views: 298

Answers (1)

Ravi B
Ravi B

Reputation: 1592

You can use this library Objective-Zip, actually I have used this and its working fine for me.

Creating a Zip File:

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

Adding a file to a zip file

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

[stream writeData:abcData]; [stream finishedWriting];

Reading a file from a zip file:

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];

Hope this code will help you :) Happy Coding!! ;)

Upvotes: 1

Related Questions