NaXir
NaXir

Reputation: 2413

Download a zip file in nsDocumentDirectory, unarchive and reading it

I have a .zip file at a URL and i want to download it, unarchive and save it into a nsdocument directory without any UI or user interaction. Then reading back.

Upvotes: 0

Views: 282

Answers (2)

Leeloo Levin
Leeloo Levin

Reputation: 443

First download the file to your device.

NSString *URLstring = @"http://your.download.URL";
NSURL  *url = [NSURL URLWithString:URLstring];
NSData *urlData = [NSData dataWithContentsOfURL:url];

Then write it to the device. Where thePath is where on you device you want to save it as well as the filename you want to save it as, remember to add the file extension (.zip).

[urlData writeToFile:thePath atomically:YES];

Then you could use something like ziparchive or minizip to unzip it. There are several open source solutions out there. These two have worked for me in the past. Easy enough to use.

After that it's simple enough to do whatever you want with the unzipped data. And do some housecleaning and delete the zip file from the phone.

Upvotes: 0

Dipen Panchasara
Dipen Panchasara

Reputation: 13600

Declare this Variable in your .h file

NSMutableData *responseData;

Write this code in your viewDidLoad Method This method will start Downloading file from Given URL

NSURL *serverURL = [NSURL URLWithString:@"your file URL here"];
NSURLRequest *request = [NSURLRequest requestWithURL:serverURL];
NSURLConnection *cn = [NSURLConnection connectionWithRequest:request delegate:self];
[cn start];

Implement this Delegate method in .m file

#pragma mark - NSURLConnection Delegate Methods
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
    NSLog(@"%s",__FUNCTION__);
    responseData = nil;
}

- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
    NSLog(@"%s",__FUNCTION__);
    responseData = [[NSMutableData alloc] initWithCapacity:0];
}

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
    NSLog(@"%s",__FUNCTION__);
    [responseData appendData:data];
}


- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
    NSLog(@"%s",__FUNCTION__);

    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *docDirPath = ([paths count] > 0) ? [paths objectAtIndex:0] : nil;
    NSString *filePath = [docDirPath stringByAppendingPathComponent:@"DownloadedZip.zip"];

    // Save file to Document Directory
    [responseData writeToFile:filePath atomically:YES];
    responseData = nil;
}

Download project to unArchive zip file here and put unArchive Code after saving file in Document Directory

Upvotes: 1

Related Questions