Search code examples
swiftxcodepffile

Save object from Parse as image instead of PFFileObject in Swift


I am trying to save images from Parse to a list. Now I am saving the images as PFFileObject, but I want to save them as uiimages instead. I am using this code:

var weblinks = [String]()
    var webnames = [String]()
    var webobjects= [PFFileObject]()
    var webimages = [UIImage]()

func fetchFromParse() {
        let query = PFQuery(className:"FirstClass")
        query.findObjectsInBackground { (objects, error) -> Void in
            if error == nil {
                for object in objects! {
                    self.webnames.append(object["webnames"]! as! String)
                    self.weblinks.append(object["weblinks"]! as! String)
                    self.webimages.append(object["webobjects"]! as! PFFileObject
                }
                self.myCollectionView.reloadData()
            } else {
                print(error!)
            }
        }
    }

How can I do to save the images to webimages instead of webobjects?


Solution

  • You can't save images as UIImage directly because Parse doesn't know what that is.

    PFFileObject exists to help you upload any kind of file, like images, as long as its converted to Data.

    Getting a Data object from an UIImage is as simple as

    let data = image.pngData()
    

    and you can initialize an image with a Data object like this

    let image = UIImage(data: data)
    

    Both methods return optionals, so you'll have to deal with that, but you can use that Data value on PFFileObject to upload your images to Parse.