Download multiple small files in background state

96 views Asked by At

Can anyone suggest a solution for downloading multiple files say 100s, in background. The important thing being that the download url has a life span of 15 minutes, so it's required that we fetch a download url and then start downloads. We can't prefetch all urls and add it to download task, as that may lead to download failures of expired url after few successful downloads.

Thanks in advance.

1

There are 1 answers

0
Wassim Seifeddine On

you can do the following:

var data : NSData?{
    didSet{
    //Parse the data to any thing you want
    }
}
var urlFetchedAsString : String? {
    didSet{
        if(urlFetchedAsString == nil)
            return
        let url : NSURL = NSURL(string: urlFetchedAsString!)!
   dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0), {
    () -> Void in
    data = NSData(contentsOfURL: url)
     })
    }
}
func fetchURL() ->String{
    //Fetched Your url and return 
}
override func  viewDidLoad(){
    super.viewDidLoad()
    urlFetchedAsString = fetchURL()
}

Explanation

  • The OS will execute the didSet block in the variable urlFetchedAsString each time it is set
  • The didSet block will fetch the data from the url and save them as NSData
  • The dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0) means that fetching data from url will be done on the different thread to prevent blocking the UI thread
  • After done saving you, the variable data will be set and the didSet for this variable will be executed. In this block you can implement your parsing algorithm.
  • Fetching the url itself is up to you because you didn't clarify where they are or how will u get them

Note

  • Here i assumed that you don't need to copy of all the urls because as you said they will expire in 15 mins