-1

I would like to retrieve 2 PFObjects at random, included in the PFObjects array when I do a query via Parse. The findObjects() option works but it creates a break when the app is running. Therefore I want to use findObjectsinbackground but when I do so it returns niL. Please note: I already implemented a function in my code that allows me to shuffle any array I get.

Would be great if you could provide me with a standard example of how to use findObjectsinbackground on a query in order to get 2 PFObjects at random among the PFObjects array. I don't think I need to provide a code for that

rici
  • 234,347
  • 28
  • 237
  • 341
DavidT.
  • 11
  • 1
  • 5
  • you need to move ALL logic depending on the retrieved items into the completion block of `findObjectsinbackground` since the call is asynchronous and returns at some arbitrary point in time after the call to findObjectsinbackground. – luk2302 Dec 23 '15 at 02:07

1 Answers1

0

Here try this:

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

        if let objects = objects {

            let firstRandom = Int(arc4random_uniform(UInt32(objects.count)))
            let firstObject = objects[firstRandom]

            var newArray = objects
            newArray.removeAtIndex(firstRandom)

            let secondRandom = Int(arc4random_uniform(UInt32(newArray.count)))
            let secondObject = objects[secondRandom]


        }

    }

Here, firstObject and secondObject are the things you are looking for.

Hope this helps.

Pranav Wadhwa
  • 7,666
  • 6
  • 39
  • 61