Question

I have a problem when downloading a file. I have a zip file that has 90 MB and it is filling my RAM memory to hudge amounts until the file is downloaded. Could somene help me with some example code that shows any better way to do this and not overload my RAM?

Thanks.

Code:

dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
dispatch_async(queue, ^{
    NSURL *url = [NSURL URLWithString:@"http://autoskola.1e29g6m.xip.io/mobileData/slike3.zip"];
    NSError *error = nil;

    NSData *data = [NSData dataWithContentsOfURL:url options:0 error:&error];


    if(!error){
        NSArray *paths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);
        NSString *path = [paths objectAtIndex:0];
        NSString *zipPath = [path stringByAppendingPathComponent:@"slike3.zip"];

        [data writeToFile:zipPath options:0 error:&error];

        if(!error){

            //unziping the files
            ZipArchive *za = [[ZipArchive alloc] init];

            if([za UnzipOpenFile:zipPath]){
                BOOL ret = [za UnzipFileTo:path overWrite:YES];

                if(NO == ret){} [za UnzipCloseFile];



            }

        }else{
            NSLog(@"Error saving file %@", error);
        }
    }else{
        NSLog(@"Error downloading zip file: %@", error);
    }


});
Was it helpful?

Solution

You may want to consider looking into AFNetworking. It's probably the most commonly used library for accessing the internet. You can use it to download a file and take the output stream and write the data into a file. This will allow you to download and write the file as chunks of data instead of all at once. You'll want to take a look at the AFNetworking Docs for information on downloading the file. You'll also want to look into the docs for NSFileHandle for information on how to write data into a file.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top