简体   繁体   中英

Parse & Swift- Randomizing images

First, to be simple, how do I change a blank UIImage view to an image I have stored in Parse? This is my code so far

   var query = PFQuery(className:"Content")
    query.getObjectInBackgroundWithId("mlwVJLH7pa") {
        (post: PFObject?, error: NSError?) -> Void in
        if error == nil && post != nil {

            //content.image = UIImage

        } else {
            println(error)
        }
    }

On top of just replacing the blank UIImageView, how may I make the image that it is replaced with random? I assume I can't use an objectId anymore, because that is specific to the row that it represents.

I would first retreive the objectIds from parse with getObjectsInBackgroundWithBlock, and then select a random objectId from that array in a variable called objectId. That way you save the user from querying every object from parse and using a lot of data doing it.

Second I would

getObjectInBackgroundWithId(objectId)
    if error == nil {
        if let image: PFFile = objectRow["image"] as? PFFile{
        image.getDataInBackgroundWithBlock {
        (imageData: NSObject?, error: NSError?) Void in ->
           if let imageData = imageData {
             let imageView = UIImageView(image: UIImage(data: imageData))
           }
        }
     }

At least this works for me.

First off, you'll want to use query.findObjectsInBackgroundWithBlock instead of using query.getObjectInBackgroundWithId .

This will get you all of your PFObjects. Grab a random PFObject from the array it returns and now you have a single random PFObject that you can set the content.image to.

Let's say your PFObject has an 'image' attribute as a PFFile (what you should be using to store images with Parse.)

Simply convert the PFFile into a UIImage by doing something similar to the following:

if let anImage = yourRandomPFObject["image"] as? PFFile {
     anImage.getDataInBackgroundWithBlock { (imageData: NSData?, error: NSError?) -> Void in

     let image = UIImage(data:imageData)
     content.image = image
     }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM