0

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


});
rmaddy
  • 314,917
  • 42
  • 532
  • 579
Ferenc
  • 367
  • 3
  • 14
  • Post some code, without it we can not see what is going on. – rckoenes Mar 28 '14 at 14:11
  • sorry about that, i pasted my code. – Ferenc Mar 28 '14 at 14:16
  • 1
    You issue is that trying to save the whole download in memory, you should never use any `*WithContentsOfURL:` for internet URL. Use `URLConnection` or `URLSession`. Beter yet use `AFNetworking` like Aaron Heyman suggested. – rckoenes Mar 28 '14 at 14:22

1 Answers1

3

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.

Aaron Hayman
  • 8,492
  • 2
  • 36
  • 63
  • I was having the same issue, I suggest taking a look at the answer to my question, it goes into a bit more detail: http://stackoverflow.com/a/22234023/480415 – RyanG Mar 28 '14 at 14:34
  • Thanks! Worked like a charm – Ferenc Mar 31 '14 at 08:43