Sto tentando di utilizzare il grand central dispatch per attendere che i file finiscano il download prima di continuare. Questa domanda è uno spin-off di questo: Swift (iOS), waiting for all images to finish downloading before returning.Swift, dispatch_group_wait non in attesa
Sto semplicemente cercando di scoprire come ottenere dispatch_group_wait (o simile) per attendere effettivamente e non solo continuare prima che i download siano terminati. Si noti che se utilizzo NSThread.sleepForTimeInterval anziché chiamare downloadImage, è sufficiente attendere.
Cosa mi manca?
class ImageDownloader {
var updateResult = AdUpdateResult()
private let fileManager = NSFileManager.defaultManager()
private let imageDirectoryURL = NSURL(fileURLWithPath: Settings.adDirectory, isDirectory: true)
private let group = dispatch_group_create()
private let downloadQueue = dispatch_queue_create("com.acme.downloader", DISPATCH_QUEUE_SERIAL)
func downloadImages(imageFilesOnServer: [AdFileInfo]) {
dispatch_group_async(group, downloadQueue) {
for serverFile in imageFilesOnServer {
print("Start downloading \(serverFile.fileName)")
//NSThread.sleepForTimeInterval(3) // Using a sleep instead of calling downloadImage makes the dispatch_group_wait below work
self.downloadImage(serverFile)
}
}
dispatch_group_wait(group, DISPATCH_TIME_FOREVER); // This does not wait for downloads to finish. Why?
print("All Done!") // It gets here too early!
}
private func downloadImage(serverFile: AdFileInfo) {
let destinationPath = imageDirectoryURL.URLByAppendingPathComponent(serverFile.fileName)
Alamofire.download(.GET, serverFile.imageUrl) { temporaryURL, response in return destinationPath }
.response { _, _, _, error in
if let error = error {
print("Error downloading \(serverFile.fileName): \(error)")
} else {
self.updateResult.filesDownloaded++
print("Done downloading \(serverFile.fileName)")
}
}
}
}
Nota: questi download sono in risposta a una richiesta HTTP POST e sto usando un server HTTP (Swifter) che non supporta operazioni asincrone, quindi ho bisogno di aspettare i download completi per completare prima di tornare una risposta (vedi la domanda originale di cui sopra per ulteriori dettagli).
Rob, ho un problema simile qui: http : //stackoverflow.com/questions/37201735/how-to-make-inner-async-request-complet-first-before-completing-outer-async-req pensi di poterti aiutare? – Pangu
Ottima risposta, questo mi ha aiutato molto a fare qualcosa di simile con Firebase. – kelsheikh
Il punto di ** 'dispatch_group_wait' può deadlock se non stai attento ** mi ha salvato! – fujianjin6471