Swift querying Parse all objects in class - swift

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
}
}

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..

Array of Parse Pointers (Swift) - is This Possible

I am working on an app where the user is connected (in) multiple school classes. Since a student will be in more than one class, am I able to set an array of pointers to an individual user or is that not possible (maybe a relation is better)?
Here is my code:
let classPointerQuery = PFQuery(className: "Classes")
classPointerQuery.whereKey("class_name", equalTo: self.classNameTextField.text!)
let classQuery = PFQuery.orQueryWithSubqueries([classPointerQuery])
classQuery.findObjectsInBackgroundWithBlock({ (results: [PFObject]?, error: NSError?) -> Void in
if let objects = results {
for object in objects {
let userInfo = PFUser.currentUser()!
userInfo["my_classes"] = object
userInfo.saveInBackgroundWithBlock({ (success: Bool, error: NSError?) -> Void in
if error != nil {
spinningActivity.hideAnimated(true)
self.displayAlert("Error", message: error!.localizedDescription)
} else if success {
spinningActivity.hideAnimated(true)
self.dismissViewControllerAnimated(true, completion: nil)
} else {
spinningActivity.hideAnimated(true)
self.displayAlert("Something Went Wrong", message: "Please try again")
}
})
}
}
})
* Note: I also tried changing - userInfo["my_classes"] = object - to - userInfo["my_classes"] = [object] - and got an error, "invalid type for key my_classes, expected *Classes, but got array (Code: 111, Version: 1.12.0)"
What I am doing here is querying for the object of the class that I want - lets say the user wants to add the class "Physics" - the query queries for the "class_name" in the Parse class "Classes" and spits out the object. This object is then set the current user's "my_classes" -> a pointer object. I there a way, when the user wants to add "Calculus" that the pointer object in Parse will have 2 pointers instead of replacing the current pointer?
Thanks in advance for the help!
you cant store Pointers in array, you can store objectID in the array as string and do the query like that.... the general rule is that u use Pointers for 1:many relationships in database and Relations in many:many...
Update 1 - Saving objectID to Array in Parse
PFUser.currentUser()!.addObject(somePFObject.objectID!, forKey: "my_classes")
for queries you will than use containedIn
querySetup.whereKey("class", containedIn: array)

Compound Query from loop - Parse 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?

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

Extra argument in Call for Parse in Swift

All I am trying to get multiple objects out of a parse database.
Here is some of my code :
So this does the query :
var MainPicture = PFQuery(className: "Staff")
MainPicture.whereKey("Position", equalTo: "Sales Manager")
MainPicture.findObjectsInBackgroundWithBlock ({(objects:[AnyObject]!, error: NSError!) in
if(error == nil){
self.getMainImageData(objects as [PFObject])
}
else{
println("Error in retrieving \(error)")
}
Then I want to get a few rows out of the query :
func getMainImageData(objects: [PFObject]) {
for object in objects {
let MainPic = object["StaffPic"] as PFFile
let MainData = object["FirstName","SecondName","Position"] as PFFile
MainPic let works, but when I try and do multiple ones like MainData , I get an error : "Extra argument in call" .. I thought this would have worked.
I suspect you cannot subscript PFObject with multiple items. It is like calling
dictionary["key1", "key2"]
That will also result in too many arguments.
It is confusing that your variables are Capitalized. They look like class names.