首页 > 解决方案 > 使用 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)
                        }
                    })
                }


               }
    }
    })

标签: iosswiftparse-platform

解决方案


您的分析是正确的,请求将以不确定的顺序完成,部分或大部分受必须返回的数据量的影响。

使用将字符串映射到 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

推荐阅读