ios - 使用 getdatainbackground 从 Parse 检索多个图像(IOS - Swift)
问题描述
我尝试使用 Parse 进行查询,其中包含一些将添加到数组中的字符串和图像。数组中的字符串都是正确的顺序,但不是图像。我认为这可能是因为某些图像比其他图像小,因此它们比预期更早地附加到数组中。有什么方法可以“节省”数组中的空间以使图像保持正确的顺序?解决这个问题可能并不难,但我是新手 :( 谢谢!
query.findObjectsInBackground (block: { (objects:[PFObject]?, error: Error?) -> Void in
for object in objects! {
DispatchQueue.global(qos: .userInteractive).async {
// Async background process
if let imageFile : PFFile = self.bild.append(object.value(forKey: "Bild") as! PFFile) {
imageFile.getDataInBackground(block: { (data, error) in
if error == nil {
DispatchQueue.main.async {
// Async main thread
let image = UIImage(data: data!)
image2.append(image!)
}
} else {
print(error!.localizedDescription)
}
})
}
}
}
})
解决方案
您的分析是正确的,请求将以不确定的顺序完成,部分或大部分受必须返回的数据量的影响。
使用将字符串映射到 UIImage 的可变字典,而不是附加 UIImage(或数据)的数组。字符串键的合理选择是 PFFile 名称。
编辑我不是 Swift 作家,但我试图表达下面的想法(不要依赖它编译,但我认为这个想法是合理的)
class MyClass {
var objects: [PFObject] = []
var images: [String: UIImage] = [:] // we'll map names to images
fetchObjects() {
// form the query
query.findObjectsInBackground (block: { (objects:[PFObject]?, error: Error?) -> Void in
self.objects = objects
self.fetchImages()
})
}
fetchImages() {
for object in self.objects! {
if let imageFile : PFFile = object["Bild"] as PFFile {
self.fetchImage(imageFile);
}
}
}
fetchImage(imageFile: PFFile) {
imageFile.getDataInBackground(block: { (data, error) in
if error == nil {
self.images[imageFile.name] = UIImage(data: data!)
// we can do more here: update the UI that with image that has arrived
// determine if we're done by comparing the count of images to the count of objects
} else {
// handle error
}
}
}
}
这将在后台获取图像并使用字典将它们与其文件名相关联。OP 代码没有解释什么self.bild
是,但我认为它是一个实例数组 retrieved PFFiles
。我用images
实例变量替换了它。
图像文件顺序由对象集合维护:获取第 N 个图像,获取第 N 个对象,获取它的“Bild”属性,PFFile 的名称是图像字典的键。
var n = // some index into objects
var object : PFObject = self.objects[n]
var file : PFFile = object["Bild"]
var name : String = file.name
var nthImage = self.images[name] // is nil before fetch is complete
推荐阅读
- javascript - 处理完数据后如何刷新kafka队列?
- c# - 如何使用 Selenium C# 将数值发送到输入标签
- c++ - 是否可以捕获全局鼠标事件
- go - 使用 govmomi 库在 golang 中的零点尊重
- apache - Roundcube 显示 net::ERR_ABORTED 403 (Forbidden) 错误
- html - 水平滚动容器?
- linux - 为什么这个程序会出现段错误?
- css - 如何重新定位 google rechapta 弹出窗口?
- android - Google Play 服务 SMS 和 CALL LOGS 权限问题
- android - 如何在Android中的两个位置之间使用折线绘制自己的路线