Downloading & Uploading Data From URL Swift Asynchronously
<p>I have an array of 5 links which contain either <code>jpg</code> or <code>mov</code> files. I want to download them into my iOS Swift app. I use the following code. </p>

<pre><code>var index = 0
while (index &lt; myLinks.count) {
if (myLinks[index].resource_type == "image") {
    let stringURL = "http://www.blablabla" + ".jpg"
    let url = NSURL(string : stringURL)
    getDataFromUrl(url!) { (data, response, error)  in
        guard let data = data where error == nil else { return }
        print(response?.suggestedFilename ?? url!.lastPathComponent ?? "")
        print("Download Finished")
        myLinks[index].image = UIImage(data: data)
    }
}
else if (myLinks[index].resource_type == "video") {
    let stringURL = "http://www.blablabla" + ".mov"
    let url = NSURL(string : stringURL)
    getDataFromUrl(url!) { (data, response, error)  in
        guard let data = data where error == nil else { return }
        print(response?.suggestedFilename ?? url!.lastPathComponent ?? "")
        print("Download Finished")
        dispatch_async(dispatch_get_main_queue(), {
            let paths = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)
            let documentsDirectory : NSString = paths[0]
            let appFile = documentsDirectory.stringByAppendingPathComponent(myLinks[index].id! + ".m4v")
            do {
                try data.writeToFile(appFile, options: .AtomicWrite)
                myLinks[index].videoURL =  NSURL(fileURLWithPath: appFile)
            }
            catch _ {
                print("error saving video")
            }
        })
    }
}

index = index + 1
}


 func getDataFromUrl(url: NSURL, completion: ((data: NSData?, response: NSURLResponse?, error: NSError? ) -&gt; Void)) {
    NSURLSession.sharedSession().dataTaskWithURL(url) {
        (data, response, error) in
        completion(data: data, response: response, error: error)
        }.resume()
}
</code></pre>

<p>Now the only problem is that, after downloading these resources, I want to display them to the user in a form of slideshow, hence I can only proceed knowing that all 5 downloads have been completed. The problem with the code above is that since the <code>getDataFromUrl</code> function is executed asynchronously, this while loop will finish executing before all of the content has actually been downloaded. </p>

<p><strong>EDIT</strong></p>

<p>Here is a code adapting the accepted answer to uploading as well. The problem is that when more than one value is in the queue, only the first task gets executed and then nothing happens. </p>

<pre><code> var uploadQueue:[UploadMessage]?
let session = NSURLSession.sharedSession()
let lockQueue = dispatch_queue_create("com.dsdevelop.lockQueue", nil)

func getRemainingActiveUploads() -&gt; Int {
    return (self.uploadQueue != nil) ? self.uploadQueue!.count : 0
}

func removeMessageFromUploadQueue(messageToBeRemoved : UploadMessage) {
    if (uploadQueue != nil) {
        dispatch_sync(lockQueue) {
            self.uploadQueue = self.uploadQueue?.filter({$0.date!.compare(messageToBeRemoved.date!) == NSComparisonResult.OrderedSame})
        }
    }
}

var uploadTimer : NSTimer?

func finishedUploading() {
    uploadTimer = NSTimer.scheduledTimerWithTimeInterval(1, target: self, selector: #selector(uploadAllLinks), userInfo: nil, repeats: false)
    if (needToRefetch) {
        needToRefetch = false
        newMessageReceived()
    }
}

func uploadAllLinks()
{
    print("uploading test")
    uploadTimer?.invalidate()
    uploadTimer = nil
    // suspending queue so they don't all finish before we can show it
    session.delegateQueue.suspended = true
    session.delegateQueue.maxConcurrentOperationCount = 1

    let myUrl = NSURL(string: "http://****")

    // create tasks
    if (uploadQueue != nil) {
        if (uploadQueue?.count &gt; 0) {
        for message in uploadQueue!
        {
            let request = NSMutableURLRequest(URL:myUrl!)
            request.HTTPMethod = "POST"
            request.timeoutInterval = 10
            request.HTTPShouldHandleCookies=false

            var postString = "sender=" + message.sender! 
            request.HTTPBody = postString.dataUsingEncoding(NSUTF8StringEncoding);

            let dltask = session.dataTaskWithRequest(request, completionHandler: { (data, response, error) in
                if data != nil
                {
                    do {
                        let jsonArray = try NSJSONSerialization.JSONObjectWithData(data_fixed!, options:[])
                        dispatch_async(dispatch_get_main_queue(), {

                            if let errorToken = jsonArray["error"] as! Bool? {
                                if  !errorToken  {
                                  self.uploadQueue = self.uploadQueue!.filter({$0.date!.compare(message.date!) != NSComparisonResult.OrderedSame})
                                                let remaining = self.getRemainingActiveUploads()
                                                print("Downloaded.  Remaining: \(remaining)")
                                                if (remaining == 0) {
                                                    self.finishedUploading()
                                                }
                                }
                                else {

                                                let remaining = self.getRemainingActiveUploads()
                                                print("Downloaded.  Remaining: \(remaining)")
                                                if (remaining == 0) {
                                                    self.finishedUploading()
                                                }
                                }
                            }
                            else {

                                            let remaining = self.getRemainingActiveUploads()
                                            print("Downloaded.  Remaining: \(remaining)")
                                            if (remaining == 0) {
                                                self.finishedUploading()
                                            }
                            }

                        })
                    }
                    catch {
                        print("Error: \(error)")
                    }
                }

            })
            print("Queuing task \(dltask)")
            dltask.resume()
        }
            session.delegateQueue.suspended = false
        }
        else {
            finishedUploading()
        }
        // resuming queue so all tasks run
    }

}
</code></pre>