URL Puller Code Challenge

Recently I found a code challenge on downloading contents in iOS. The goal of this challenge is to create a class that downloads an array of URLs asynchronously and store the downloaded contents in a designated directory with unique file names.

Here is my solution:

  1. Set up a NSOperationQueue property. I figured each URL will fire off a download task, however the download class will only have one operation queue. It sounds reasonable to make it a property so that I can mange the download queue later on.

2. Create an initializer method to basically initialize the operation queue.

3. Create a download method. This method takes in an array of URLs, and each URL should trigger a download job. Here I call addOperationWithBlock: on the operation queue property to fire off each download task. Note I have a helper method generatePathForURL: to create the file path in documents directory. I will reveal this method later.

4. Create a wait method. The purpose of this method is to block further process until all downloads are finished. This is where the operation queue property becomes useful. Simply calling waitUntilAllOperationsAreFinished on the property will trigger the wait.

5. Create a validation method for file existence check. This method will check whether the physical file has been downloaded in the documents directory. Once again I am generating file path using helper method generatePathForURL:.

6. Finally, I have two helper methods. To generate the file path in the documents directory I first call the sha1: method to create sha1 string of the download url.

How to use? Here is an example:

Github Gist:

Final thoughts…

I could use AFNetworking/AFURLSessionManager to make it better, but that’s for another day.

Like what you read? Give Leo Feng a round of applause.

From a quick cheer to a standing ovation, clap to show how much you enjoyed this story.