简体   繁体   中英

Memory pressure downloading many images

I am trying to download thousands of pictures (Maximum 350 Kb each) from the server, but I go by over a thousand images I receive the alert "Memory Presure".

Basically I have an array with all the names of the images and do a loop to bring one to one like this:

for (int x=0; x<unique.count; x++) {

     NSURL *ImageLink = [NSURL URLWithString:[NSString stringWithFormat:@"http://urltoimagesfolder.com/", [unique objectAtIndex:x]]];
     NSData *data = [NSData dataWithContentsOfURL:ImageLink];
     UIImage *img = [[UIImage alloc] initWithData:data];

     if (data.length !=0) {

     NSString *fullPath = [documentsDirectory stringByAppendingPathComponent:[unique objectAtIndex:x]]; //add our image to the path

     [UIImageJPEGRepresentation(img, 1.0) writeToFile:fullPath atomically:YES];

     //[self saveImage:img :NombreFoto];
     //[self Miniatura:img :[NSString stringWithFormat:@"mini-%@", [unique objectAtIndex:x]]];
     }

    data = nil;
    img = nil;


}

Question: How I can download all the images without the app crash with memory pressure?

UIImageJPEGRepresentation() may cause the memory overflow. But you don't need to use that function, you can check if the received data is image and write its bytes directly to disk via sending message writeToFile: to data object.

You can fix you code like this:

for (int x=0; x<unique.count; x++) {
     NSURL *ImageLink = [NSURL URLWithString:[NSString stringWithFormat:@"http://urltoimagesfolder.com/", [unique objectAtIndex:x]]];
     NSData *data = [NSData dataWithContentsOfURL:ImageLink];
     if (data.length !=0) {

         UIImage *img = [[UIImage alloc] initWithData:data];
         if (img) {
             NSString *fullPath = [documentsDirectory stringByAppendingPathComponent:[unique objectAtIndex:x]]; //add our image to the path
             [data writeToFile:fullPath atomically:YES];
         }
         img = nil;

     }
     data = nil;
}

However this is not the optimal solution. -dataWithContentsOfURL: is synchronous method and will stop execution of your main thread while downloading the file. As a consequence the UI will hang during the download. To make your UI not to hang you can use asynchronous url requests.

See -sendAsynchronousRequest:queue:completionHandler: method of the NSURLConnection class. Or if your app is only for iOS 7 see -dataTaskWithURL:completionHandler: as alternative.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM