Parse.com PFQuery order by time (Swift) - 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")

Related

swift parse query not returning objects in ascending order

My query aims to fetch the objects created by a certain number of users. The following are my codes:
var dates = [NSDate]()
var messages = [String]()
let getUsersQuery = PFQuery(className: "followings")
getUsersQuery.whereKey("follower", equalTo: PFUser.currentUser()!.objectId!)
getFollowedUsersQuery.findObjectsInBackgroundWithBlock { (objects, error) -> Void in
if let objects = objects {
for object in objects {
let followedUser = object["followedUser"] as! String
let getPostsQuery = PFQuery(className: "posts")
getPostsQuery.whereKey("userId", equalTo: followedUser)
getPostsQuery.orderByDescending("updatedAt")
getPostsQuery.findObjectsInBackgroundWithBlock({ (objects, error) -> Void in
if let objects = objects {
for post in objects {
self.dates.append(post.createdAt as NSDate!)
self.messages.append(post["message"] as! String)
}
print(self.dates)
self.myTableView.reloadData()
})
}
}
}
})
Here's what come up when I print the dates in the log:
However, the content in my tableview is not in an ascending order. In fact the post created most recently is at the bottom of the tableview. One thing I noticed is that the posts of a particular user seems to be shown together. So all of one user's post would appear at the top of the tableview no matter another user has created the newest post. Any idea what is going wrong? thanks!
What you need is a nested query. The array you are trying to get is an of posts. So your query should be on the post table. (Also, your table should be called post not posts. Table names should always be singular. Each post is called a post not a posts.
let postsQuery = PFQuery(className: "post")
postsQuery.orderByDescending("updatedAt")
let usersQuery = PFQuery(className: "following")
usersQuery.whereKey("follower", equalTo:PFUser.currentUser()!.objectId!)
// this might need to change depending on what the followed user is called in the `followings` table.
postsQuery.whereKey("userId", matchesKey:"followed", inQuery:usersQuery)
getPostsQuery.findObjectsInBackgroundWithBlock({ (objects, error) -> Void in
if let objects = objects {
for post in objects {
self.dates.append(post.createdAt as NSDate!)
self.messages.append(post["message"] as! String)
}
print(self.dates)
self.myTableView.reloadData()
})
Also, you are saving dates and messages in separate arrays. Create a struct or something that has a date and string and have a single array of Post objects.

PFQuery categorizing results into multilevel arrays

I am trying to do a multiple PFQuery and storing the data properly.
My plan is to query for group members in my Group
I am looking for the key member. It gives me an array of objectIds. Then I want to query in my _User class for their picture with key firstImage. Displaying the data is not the problem, just getting it the right way.
The data needs to be stored considering it's groups. This is what i tried so far:
let fetchGroupsQuery = PFQuery(className: "Group")
fetchGroupsQuery.whereKey("member", equalTo: objectID!)
fetchGroupsQuery.findObjectsInBackgroundWithBlock { (objects, error) -> Void in
if error != nil
{
}
else {
if let objects = objects {
self.memberPhotos.removeAll()
for object in objects {
if let member = object["member"] as? [String]
{
// returns array of objectIds
for user in member
{
// returns single ids
self.groupIds.append(user)
let photoQuery = PFUser.query()
photoQuery?.whereKey("objectId", equalTo: user)
photoQuery?.findObjectsInBackgroundWithBlock({ (results, error) -> Void in
if error != nil {
// ....
}
else {
self.memberPhotos.removeAll()
if let results = results
{
for result in results
{
if result["firstImage"] != nil
{
self.memberPhotos.append(result["firstImage"])
}
}
}
}})
}
}
My idea was to store the data within an array of arrays.
So that I can later go into array[indexPath.row] to get the array I need to loop through in order to get the right group pictures.
Any ideas how to solve this?
I would use two separate queries function:
1) to get their ID's
2) for their pictures.
For the first query: what you need to change?
Your objectID array should be of type of NSMutableArray because in order to fetch their info you should use the constraint whereKey containedIn not whereKey equalTo
and for that constraint you should downcast your NSMutableArray to type AnyObject.
Also change the Type of your groupIds to NSMutableArray, then append your array.
For the Second query:
Since your groupIds Type is already NSMutableArray just cast it to AnyObject,then use the whereKey containedIn
Note: It would be better to download all images before appending your
array. So you have the option of using struct or class(easier to
group data to its owner) then create an array of that data
structure.Where it because easier to populate your UI.

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?

Parse includeKey works for an Array but not for a Pointer Object

I am currently working on an iOS app that connects to Parse and I am having difficulty in retrieving objects using the includeKey() function.
Lets say that I am adding a food item to my Food table:
var newFoodObject = PFObject(className: "Food")
//Here I am pointing to an existing object in my SubCategory table
newFoodObject["subCategory"] = PFObject(withoutDataWithClassName: "SubCategory", objectId: "oisii1pZSP")
newFoodObject.saveInBackgroundWithBlock { (success: Bool!, error:NSError!) -> Void in
println(success)
println(error)
}
Then lets say I want to retrieve that object:
var query = PFQuery(className: "Food")
query.includeKey("subCategory")
query.findObjectsInBackgroundWithBlock { (objects:[AnyObject]!, error:NSError!) -> Void in
println(objects)
println(error)
}
For some reason when I do this the SubCategory object is not included in the query coming back unless I save the SubCategory in an array in my Food table.
Any thoughts why the includeKey() functions works with an array of pointers but not with a single pointer?

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