0

I can get images using the following code. But, this is loading all images first. How can I get only one random image? I tried many ways, but I couldn't. Please fix code and help me.

func loadData() {

    let query: PFQuery = PFQuery(className: "Posts1")
    query.findObjectsInBackgroundWithBlock { (objects, error) -> Void in

        if (error == nil){
            for object in objects! as [PFObject]{

                let imagefile = object["imageFile"] as! PFFile?

                imagefile?.getDataInBackgroundWithBlock({

                    (imageData, error) -> Void in
                    if (error == nil) {
                        self.cameraView.image = UIImage(data:imageData!)
                    }
                })
            }
        }
        else{
        }
    }
}
Makoto
  • 3
  • 2

2 Answers2

0

Because this line

for object in objects! as [PFObject]

means take every object and perform action described in for body. take random object from that collection instead, there are a lot of answers which can help you, like this one Pick a random element from an array

Community
  • 1
  • 1
ReDetection
  • 3,146
  • 2
  • 23
  • 40
0

There isn't a way to get random objects from a PFQuery, but you can fake it like this:

PFQuery *query = [PFQuery queryWithClassName:@"Posts1"];
dispatch_async(dispatch_get_global_queue( DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
  NSInteger count = [query countObjects];
  query.skip = arc4random_uniform(count);
  PFObject *object = [query getFirstObject];
  PFFile *file = object[@"imageFile"];
  NSData *data = [file getData];
  UIImage *image = [UIImage imageWithData:data];
  // Do whatever you want with the image
  // You should probably return to the main queue here
});
EmilioPelaez
  • 18,758
  • 6
  • 46
  • 50