我必须使用以下代码从数据库中获取一堆图像,其中url是一个数组,具有指向Firebase存储上图像的链接。
func downloadFromServer(url: [String], imageNumber: Int){
for i in url{
let i = URL(string: i)
print("I" , i)
URLSession.shared.dataTask(with: i!) { data, response, error in
guard
let httpURLResponse = response as? HTTPURLResponse, httpURLResponse.statusCode == 200,
let data = data, error == nil,
let image = UIImage(data: data)
else { return }
print("Here", image)
DispatchQueue.main.async() {
print("Appended")
imageArrayWatch.append(image)
//imageArr.append(image)
}
}.resume()
}
}
我希望我的应用程序在从数据库中获取图像时显示加载屏幕。但是,当我尝试像这样在视图控制器中调用showSpinner
时
self.showSpinner(onView: self.view)
downloadFromServer(url: imageName)
self.removeSpinner()
显示和删除微调功能仅显示加载屏幕。这是行不通的,因为在从数据库中获取所有图像之前,我的downloadFromServer函数已经退出,我只能看到加载屏幕一秒钟。在将所有图像都附加到mageArrayWatch
数组时,如何使加载屏幕完成?
答案 0 :(得分:2)
您需要一个调度组
var imageArrayWatch = [UIImage]()
func downloadFromServer(url: [String], imageNumber: Int){
let g = DispatchGroup() ////// 1
for i in url{
let i = URL(string: i)
print("I" , i)
g.enter() ////// 2
URLSession.shared.dataTask(with: i!) { data, response, error in
guard
let httpURLResponse = response as? HTTPURLResponse, httpURLResponse.statusCode == 200,
let data = data, error == nil,
let image = UIImage(data: data)
else { g.leave() ; return } ////// 3
print("Here", image)
DispatchQueue.main.async() {
print("Appended")
self.imageArrayWatch.append(image)
g.leave() ////// 4
}
}.resume()
}
g.notify(queue: .main) { ////// 5
// stop loading here
}
}