我设法从Firebase中获取了一个URL列表,并将它们附加到一系列链接。
var fileArray = [storiesContent]()
func GetTheStories() {
let ref = FIRDatabase.database().reference().child("Content")
ref.observe(FIRDataEventType.value, with: {(snapshot) in
if snapshot.childrenCount>0{
for content in snapshot.children.allObjects as![FIRDataSnapshot]{
let contentInfo = content.value as? [String: AnyObject]
let contentType = contentInfo?["contentType"]
let storyLink = contentInfo?["pathToImage"]
let content = storiesContent(storyUrl: storyLink as! String?)
self.fileArray.append(content)
}
}
})
}
接下来,我创建了一个扩展,以便从链接下载图像作为UIImageView&#39>
let imageCache = NSCache<AnyObject, AnyObject>()
extension UIImageView {
func downloadImage(fromm imgURL: String!){
let url = URLRequest(url: URL(string: imgURL)!)
image = nil
if let imageFromCache = imageCache.object(forKey: imgURL as! AnyObject!) as? UIImage{
self.image = imageFromCache
return
}
let task = URLSession.shared.dataTask(with: url){
(data, response, error) in
if error != nil {
print(error!)
return
}
DispatchQueue.main.async {
let imageToCache = UIImage(data: data!)
imageCache.setObject(imageToCache!, forKey: imgURL as! AnyObject!)
self.image = imageToCache
}
}
task.resume()
}
此扩展程序在用于下载图像并在表格视图中显示时有效。但是,我不确定它是否正在下载图像并将它们附加到阵列。
我创建了一个数组来将UIImageView附加到
var picArray: [UIImageView] = []
然后我尝试创建一个函数,它将从链接数组中下载图像,然后将它们附加到UIImageView数组
func downloadImages() {
if (countInt <= picArray.count - 1){
let imageToInsert = UIImageView()
imageToInsert.downloadImage(fromm: fileArray[countInt].storyUrl!)
countInt = countInt + 1
picArray.insert(imageToInsert, at: 0)
print("Image downloaded. Current count: \(picArray.count)")
self.downloadImages()
}
else{
print("no more items")
countInt = 0
}
但是当我调用这个函数时,似乎什么也没发生。我完全错误地采取了这种方式吗?我的最终目标是将图像附加到UIImage数组,但我们的扩展仅处理UIImageView。有没有人有什么建议?