iOS
iOS

Reputation: 3616

iOS best way to download bulk images

In my app, I have to download nearly 500 images as I open a ViewController. Downloading all 500 images at a time is not a right idea. I'd like to keep 5 active asynchronous downloads at a time. When any one in five is completed, it should start the next.

I also have a refresh control which will restart downloading all the images from first.

Which technique I could go for to implement this modal?

Here is what I tried so far,

Semaphore is created in property declaration

private var semaphore = dispatch_semaphore_create(5)

After getting web service response,

private func startDownloadingImages() {
        for place in places {
            dispatch_semaphore_wait(self.semaphore, DISPATCH_TIME_FOREVER)
            self.downloadImageForPlace(place)
        }
    }

private func downloadImageForPlace(place: Place) {
        ApplicationControls.getImageForPlace(place, withCompletion: { (image, error) -> () in
            // error checks
            dispatch_async(dispatch_get_main_queue(), {
                // UI update
                dispatch_semaphore_signal(self.semaphore)
            })
        })
    }

But when I tap refresh control, app locks at dispatch_semaphore_wait and I could able to find a way to reset semaphore.

Upvotes: 1

Views: 1385

Answers (1)

ben
ben

Reputation: 890

I would use an OperationQueue like this

let queue = OperationQueue()
queue.maxConcurrentOperationCount = 5;

for url in imageUrls {
    queue.addOperationWithBlock { () -> Void in

        let img1 = Downloader.downloadImageWithURL(url)

        NSOperationQueue.mainQueue().addOperationWithBlock({
            //display the image or whatever
        })
    }


}

you can stop your operations with this

queue.cancelAllOperations();

and then just restart the whole thing.

The only thing that you have to change is that your requests have to be synchronous then. Because this approach wont work with callbacks.

Upvotes: 2

Related Questions