Compound Query from loop - Parse Swift - swift

In the app Im working on, users select a set of "tags" among a list, then I need to query all items which include at least one of those tags.
To do so, I want to use compound queries.
documentation from Parse.com
var lotsOfWins = PFQuery(className:"Player")
lotsOfWins.whereKey("wins", greaterThan:150)
var fewWins = PFQuery(className:"Player")
fewWins.whereKey("wins", lessThan:5)
var query = PFQuery.orQueryWithSubqueries([lotsOfWins, fewWins])
query.findObjectsInBackgroundWithBlock {
(results: [PFObject]?, error: NSError?) -> Void in
if error == nil {
// results contains players with lots of wins or only a few wins.
}
}
my issue here is that my tags are in an array, and I don't know how much there is (could be 1, could be 3). So I though about doing a for loop to create a query for every one of them.
my problem is that I can't access the variable outside of this for loop, and I can't declare them before hand as I don't know how much there will be.
something that would look like this.
for(var i = 0; i < tags.count; i++){
let i = PFQuery(className: "items")
i.whereKey("tags", equalTo: tags[i])
}
var query = PFQuery.orQueryWithSubqueries([variable1, variable2 ... ])
query.findObjectsInBackgroundWithBlock {
(results: [PFObject]?, error: NSError?) -> Void in
if error == nil {
// results
}
}
is there a way to achieve such thing?

Related

Swift Parse Query Using A Pointer

I have to query for a class called "Commitment" it has a pointer called "need". I need to be able to access the data in the pointer of need while querying Commitment. I have to query for Commitment because I have to check the "committer" object against the current user. Essentially I want to be able to see the needs that the current user has committed to.
Commitment Class:
Need Class:
let query = PFQuery(className: "Commitment")
query.order(byDescending: "createdAt")
query.whereKey("committer", equalTo: PFUser.current()!)
query.includeKey("need")
query.findObjectsInBackground {
(objects: [PFObject]?, error: Error?) -> Void in
if let objects = objects as [PFObject]? {
self.committment = []
self.commitObject = []
for object in objects {
self.committment.append(Committment(id: object.objectId!, needName: object["needName"] as! String))
self.commitObject.append(object)
}
self.tableView.reloadData()
} else {
print("failure")
}
}
This is my current query. It returns nil on needName so obviously that isn't working. Any help is appreciated.
The reason that you get nil is because you are not accessing the need object but you are trying to get it from the Commitment object
just change your code to something like this:
let query = PFQuery(className: "Commitment")
query.order(byDescending: "createdAt")
query.whereKey("committer", equalTo: PFUser.current()!)
query.includeKey("need")
query.findObjectsInBackground {
(objects: [PFObject]?, error: Error?) -> Void in
if let objects = objects as [PFObject]? {
self.committment = []
self.commitObject = []
for object in objects {
let need = object["need"] as [PFObject]?
self.committment.append(Committment(id: object.objectId!, needName: need["needName"] as! String))
self.commitObject.append(object)
}
self.tableView.reloadData()
} else {
print("failure")
}
}
Notice that i first access the need object and from there extract the needName property.
BTW! i am not sure that the syntax is 100% accurate (i wrote it in freestyle) but i am sure that you got the idea..

Value of optional type PFQuery? not unwrappped

I updated to the latest version of Swift/XCode and a PFQuery in my app is generating an error: Value of optional type 'PFQuery?' not unwrapped. I know I could add a bang (!) but this only makes the error goes away. It doesn't actually fix the problem. The query used to return results before I upgraded. Here's the code in question:
PFGeoPoint.geoPointForCurrentLocationInBackground { (geopoint, error) -> Void in
println(error)
if error == nil {
println(geopoint)
if var user = PFUser.currentUser(){
user["location"] = geopoint
var query = PFUser.query()
query.whereKey("location", nearGeoPoint:geopoint) //error on this line
query.limit = 10
query.findObjectsInBackgroundWithBlock({ (users, error) -> Void in
Instead of simply making it query!.whereKey(etc) what's the best way to fix this?
Thanks!
Thank you for asking, as it is all too tempting just to force-unwrap. Do it like this:
if var query = PFUser.query() {
query.whereKey("location", nearGeoPoint:geopoint)
// ... and so on
}
(It is odd that you do not know this, since you are doing it correctly just two lines before with PFUser.currentUser(). A case of the left brain not knowing what the right brain is doing?)

Parse.com PFQuery order by time (Swift)

I'm trying to get all the objects depeding on how recently they were created but its always returning from the start and i want latest first, here is my code
var query:PFQuery = PFQuery(className: "Notes")
query.orderByDescending("CreatedAt")
query.findObjectsInBackgroundWithBlock{ (objects,error) -> Void in
if error == nil {
for object in objects {
self.array.addObject(object)
}
}
}
I tried ascending order but still returns same objects.
I think the problem is just that "createdAt" field starts with a lowercase 'C', not an uppercase, so you should try:
query.orderByDescending("createdAt")

Get data from Parse Array into local CGFloat Array

Im having trouble with Swift and Parse.com array because the documentation does not say much about the Syntax and im pretty new to Swift.
So what i want to do:
I want to add two values from two CGFloats to my Database.
Later i want to pull this two Values out from Parse Database and write them into a local CG Float array. But im Having a lot of trouble
Here is my Code for uploading the Value to the Parse.com Array: (This works fine, i have the three values in my Pase Database)
var positionAx : CGFloat = -1000
var positionAy : CGFloat = -1000
var post = PFObject(className: "Post")
post["antwortA_koord"] = [positionAx, positionAy, 0]
post.saveInBackgroundWithBlock{(success: Bool!, error: NSError!) -> Void in
if success == false {
self.displayAlert("Could not post your Question", error: "Please check your internet connection")
}
else {
println("You have posted")
}
And here the Code for Getting the data from Parse.com
var buttonA = [CGFloat] ()
var query = PFQuery(className:"Post")
query.whereKey("user", notEqualTo: PFUser.currentUser().username)
query.limit = 1
query.findObjectsInBackgroundWithBlock{
(objects: [AnyObject]!, error: NSError!) -> Void in
if error == nil {
for object in objects {
self.buttonA.append(object["antwortA_koord"] as CGFloat)
println(self.buttonA)
}
I get an error in this line: self.buttonA.append(object["antwortA_koord"] as CGFloat) but i dont know how to write the Syntax in the right way.
I hope you can help me

Swift querying Parse all objects in class

I have an app that I need to grab all values in the class. I need to get "players" and "total" from the class "runningTotal". Here is the code I have:
var query = PFQuery(className:"runningTotal")
query.selectKeys(["players", "total"])
query.findObjectsInBackgroundWithBlock
{
(objects: [AnyObject]!, error: NSError!) -> Void in
if error == nil
{
self.test = objects[0]["total"]
}
}
I want to set a variable (test) equal to the result of total. I would also want to do this with players. I don't think the above code is right, as it doesn't work. I obviously don't need any constraints as I want to fetch all of the results from this class. How would I go about solving this?
Thanks for any help in advance!
As long as your query is error free, you'll need to iterate through the objects array. As you iterate through each object, which will be of type AnyObject, you will need to cast the object as a PFObject. Then you will be able to grab the data you require from it.
var query = PFQuery(className:"runningTotal")
query.findObjectsInBackgroundWithBlock {
(objects: [AnyObject]!, error: NSError!) -> Void in
if error == nil{
for object in objects{
if let data = object as! PFObject{
//Set test to total (assuming self.test is Int)
self.test = data["total"] as! Int
}
}
}else{
//Handle error
}
}