使用 getdatainbackground 从 Parse 中检索多个图像 (IOS - Swift)

Retrieve multiple images from Parse with getdatainbackground (IOS - Swift)

我尝试使用 Parse 进行查询,其中包含一些将添加到数组中的字符串和图像。数组中的字符串的顺序都是正确的,但图像不是。我认为这可能是因为某些图像比其他图像小,因此它们比预期更早地附加到数组中。有没有什么办法可以在数组中 "save" space 使图像保持正确的顺序?解决这个问题可能并不难,但我是新手 :( 谢谢!

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 名称。

EDIT 我不是 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 是什么,但我假设它是检索到的 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