私は、グランドセントラルディスパッチを使用してファイルのダウンロードが完了するのを待ってから続行します。この質問は、これからのスピンオフです:Swift (iOS), waiting for all images to finish downloading before returning。Swift、dispatch_group_wait not waiting
私は、実際に待機するためにdispatch_group_wait(または同様のもの)を取得する方法を見つけようとしており、ダウンロードが完了する前に続行するだけではありません。 downloadImageを呼び出す代わりにNSThread.sleepForTimeIntervalを使用すると、それは正常に待機することに注意してください。
私には何が欠けていますか?
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)")
}
}
}
}
注:これらのダウンロードは、HTTP POSTリクエストに応答していると私は非同期操作をサポートしていないHTTPサーバ(迅速確実)を使用していますので、私は完全ダウンロードを返す前に完了するのを待つ必要がありますかレスポンス(上記のオリジナルの質問を参照してください)
ロブは、私はここで同様の問題があります。http ://stackoverflow.com/questions/37201735/how-to-make-inner-async-request-complete-first-before-completing-outer-async-reqあなたが助けることができると思いますか? – Pangu
偉大な答え、これはFirebaseと似たようなことをやってくれました。 – kelsheikh
** 'dispatch_group_wait'のポイントは、あなたが慎重でないとデッドロックする可能性があります**私を救った! – fujianjin6471