下载阵列中的所有图像后返回功能[AlamofireImage]

时间:2015-12-16 05:19:18

标签: swift alamofire

我目前有一个带有completionHandler的函数,它应该从数组中返回下载图像的数量但不幸的是函数返回得太早而且计数总是 0 (似乎completionHandler值正在在函数完成之前返回。我该如何解决这个问题?)

func loadFunctions(){
     //Append results to data array
    getData{sta in
        if (sta == 0){
            self.downloadImages{ handler in
                print(handler)
            }
        }
    }
}
func downloadImages (completionHandler: (Int) -> ()) -> () {
    for index in data {
        let URLRequest = NSURLRequest(URL: NSURL(string: index.artworkUrl512)!)
        downloader.downloadImage(URLRequest: URLRequest) { response in
            if let image = response.result.value {
                cardImages.append(image)
                print(image)
            }
        }
    }
    completionHandler(cardImages.count)
}

使用信号量的功能

 func downloadImages (completionHandler: (Int) -> ()) -> () {
        let semaphore = dispatch_semaphore_create(0)

        for index in data {
            dispatch_semaphore_signal(semaphore)

            let URLRequest = NSURLRequest(URL: NSURL(string: index.artworkUrl512)!)
            downloader.downloadImage(URLRequest: URLRequest) { response in
                if let image = response.result.value {
                    cardImages.append(image)
                    print(image)
                }
            }
        }
        dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER)
        completionHandler(cardImages.count)
    }

0 个答案:

没有答案