I need to do two things in the same Parse query. 1) I need to find the total number of objects returned by the given query; and 2) Only display the first 20 objects. I can't do both by setting query.limit = 20because the total number of objects will only be 20. If the total number of objects is 100, I need to get that number.
So, how can I progammatically display only the first 20 objects while still receiving all 100?
var query = PFQuery(className: "Professions")
query.whereKey("user", equalTo: PFUser.currentUser()!.username!)
query.orderByDescending("createdAt")
// query.limit = 20
query.findObjectsInBackgroundWithBlock({ (objects, error) -> Void in
if error == nil {
if let objects = objects as? [PFObject] {
for object in objects {
// I tried using something like:
// for var i = 0; i <= 20; i++ {
// if object[i] {
// But get 'Int' is not convertible to 'String'
if let title = object["title"] as? String {
println(title)
}
}
}
} else {
println(error)
}
})
When I try setting the following, I always get fatal error: array index out of range.
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 20
}
Maybe not the most elegant solution, but i think you need to do two querys on the same query. One for the object.count and one with query.limit.
var query = PFQuery(className: "Professions")
query.whereKey("user", equalTo: PFUser.currentUser()!.username!)
query.orderByDescending("createdAt")
query.findObjectsInBackgroundWithBlock({ (objects, error) -> Void in
if error == nil {
if let objects = objects as? [PFObject] {
var numberOfObjects = objecs.count
}
else {
println(error)
}
query.limit = 20
query.findObjectsInBackgroundWithBlock {
(objects: [AnyObject]?, error: NSError?) -> Void in
if error == nil {
if let objects = objects as? [PFObject] {
for object in objects {
if let title = object["title"] as? String {
println(title)
}
}
}
else {
println(error)
}
}
})
First, if you just need to count objects, Parse has a method for that:
query.countObjectsInBackgroundWithBlock
Then you can issue another PFQuery to get the first 20 objects. Fetching all the objects just to count them locally is bad design.
Nonetheless, if you still have good reason to retrieve all objects (limited by Parse at 1000) and process them locally, getting the first 20 is not done with Parse, it's done in Swift, locally, after you have fetched all objects.
var fetchedProfessions = [PFObject]()
var query = PFQuery(className: "Professions")
query.whereKey("user", equalTo: PFUser.currentUser()!.username!)
query.orderByDescending("createdAt")
query.limit = 100
query.findObjectsInBackgroundWithBlock({ (objects, error) -> Void in
if error == nil {
if let objects = objects as? [PFObject] {
// Capture your results
self.fetchedProfessions = objects
}
} else {
print(error)
}
})
// Get the first 20
let firstTwentyProfessions = retrievedObjects[0..19]
Related
Several days I'm trying to crack why my code doesn't work and everything I've tried doesn't give me any result. Heres the deal:
There is a Booking class that contains userFrom who made booking
let query = PFQuery(className: "Booking")
query.whereKey("offer", equalTo: offer.pfObject!)
if self.typeOfUser == .COOK { //! If user is a Cook
query.findObjectsInBackgroundWithBlock({ (objects : [PFObject]?, error : NSError?) -> Void in
if let error = error {
print(error.localizedDescription)
} else {
if let objects = objects {
self.bookings = objects
self.usersIds = [String]()
for object in objects {
let userFrom = object.objectForKey("userFrom") as? PFObject
let userId = userFrom!.objectId! as String
self.usersIds.append(userId)
}
self.getUserInfoForBooking()
} else {
print("Something went wrong")
}
}
})
}
From every user I get objectId and append it to the [String] array. Then I query users with their IDs
private func getUserInfoForBooking() {
let userQuery = PFQuery(className: "User")
userQuery.whereKey("objectId", containedIn: self.usersIds)
userQuery.findObjectsInBackgroundWithBlock({ (objects : [PFObject]?, error : NSError?) -> Void in
if let error = error {
print(error.localizedDescription)
} else {
print(objects!)
if let objects = objects {
for object in objects {
self.users.append(object)
}
self.collectionView.reloadData()
}
}
})
}
In this query I always get an empty array.
Whatever I did, whatever I've changed always [] in response :(
This is the wrong way to query users
let userQuery = PFQuery(className: "User")
Because the class name is private. You should be creating the query as
let userQuery = PFUser.query()
I am facing an issue when trying to delete objects from Parse after having queried them.
My code:
var query = PFQuery(className:"sendMessage")
query.whereKey("messageSent", equalTo: PFUser.currentUser()!.username!)
query.whereKey("messageReceived", equalTo: self.nameLabel!.text!)
query.findObjectsInBackgroundWithBlock({ (objects, NSError) -> Void in
if objects != nil {
if let objects = objects as? [PFObject] {
for object in objects {
print(object["message"])
/// here I would go: object.deleteInBackground()
object.save()
}
}
}
})
But it seems that I cannot find the right way to do so. Any insights ?
var query = PFQuery(className:"sendMessage")
let username = PFUser.currentUser()?.username
query.whereKey("messageSent", equalTo: username)
query.whereKey("messageReceived", equalTo: self.nameLabel!.text!)
query.findObjectsInBackgroundWithBlock({ (objects:[AnyObject]?, error:NSError) -> Void in
if error == nil {
if let objects = objects as? [PFObject] {
for object in objects {
let deletemessage = object["message"] as! String
print(deletemessage)
object.delete()
}
}
}
else {
println("Error")
}
})
I have used deleteEventually() with success before, together with PFObject(withoutDataWithClassName: YourClassName, objectId: YourObjectID).
If that works I wouldn't know why, but well :)
(as stated by Hector in this Parse Question (Objective-C): https://www.parse.com/questions/delete-row)
for object in objects {
print(object["message"]
var toDelete = PFObject(withoutDataWithClassName: "sendMessage", objectId: object.objectID)
toDelete.deleteEventually()
}
func queryForPhotosFromLocalDatastore()
{
var xquery = PFQuery(className: "Follows")
xquery.fromLocalDatastore()
//xquery.whereKey("Follower", equalTo: PFUser.currentUser()!.objectId!)
xquery.findObjectsInBackgroundWithBlock { (objects, error) -> Void in
if let xobjects = objects
{
if xobjects.count > 0
{
for yobject in xobjects
{
println("Done")
}
}
else
{
println("number of objects is \(xobjects.count)")
}
}
else
{
println(error?.userInfo)
}
}
}
func queryForPhotosFromParse()
{
PFObject.unpinAllObjectsInBackgroundWithBlock(nil)
var xquery = PFQuery(className: "Follows")
xquery.whereKey("Follower", equalTo: PFUser.currentUser()!.objectId!)
xquery.findObjectsInBackgroundWithBlock { (objects, error) -> Void in
if let xobjects = objects
{
println("xobjects are \(xobjects.count)")
println("querying from parse")
for yobject in xobjects
{
var followedUser = yobject["Following"] as! String
var query = PFQuery(className: "Images")
query.whereKey("userID", equalTo: followedUser)
query.orderByDescending("createdAt")
query.findObjectsInBackgroundWithBlock { (xobjects, error) -> Void in
if let objects = xobjects
{
PFObject.pinAllInBackground(objects, block: { (success, error) -> Void in
if error == nil
{
println("Pinned \(objects.count) objects")
self.queryForPhotosFromLocalDatastore()
}
})
}
else
{
println(error?.userInfo)
}
}
}
}
}
}
// The number of objects its returning (xobjects.count) is 0. Why is that so ?
I tried to have query localdatastore in my app but The number of objects its returning (xobjects.count) is 0. Why is that so ?
i have tried to query before with the previous versions but same thing happened. The latest version on parse says that they have fixed the error but I'm still getting the number of objects retrieved from localdatastore as "0". Please Help.
I don't know How to get Top-50 query with Parse.com,
so Can you tell me that?
This code is get all query,but I'd like to get top-50 query.
But I don't how to get Top-50 or latest-50 query.
func loadData() {
comments.removeAllObjects()
var query:PFQuery = PFQuery(className: "Comment")
query.orderByDescending("createdAt")
query.limit = 1000
query.findObjectsInBackgroundWithBlock{(objects: [AnyObject]!, error: NSError!) -> Void in
if (error != nil){
//error
}
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)) {
// Task
for object in objects {
if object["commentId"] as? String == nil {
self.comments.addObject(object)
if self.comments.count == 50 {
break
}
}
}
dispatch_async(dispatch_get_main_queue()) {
// UI
self.tableView.reloadData()
self.stopIndicator()
}
}
}
}
Language is Swift.
Please answer me.
To query for the latest 50 records on Parse you need to limit the query for 50 objects (Default limit is 100).
func loadData() {
self.comments.removeAllObjects()
var query:PFQuery = PFQuery(className: "Comment")
query.orderByDescending("createdAt")
query.limit = 50 //<--- change this line
query.findObjectsInBackgroundWithBlock{(objects: [AnyObject]!, error: NSError!) -> Void in
if (error != nil){
//error
}
// Add the received objects to your array
self.comments.addObjectsFromArray(objects)
// No need to perform any task in background thread, so update the UI
self.tableView.reloadData()
self.stopIndicator()
}
}
Hi my query is very simple.
I basically want to return the objects ordered by the distance from the user.
If I pass in a PFGeoPoint, the query will return nothing. There are no errors.
If I don't put in a PFGeoPoint the query returns objects.
Whats going on?
Thanks :)
var query = PFQuery(className: "resorts")
query.whereKey("geoPoint", nearGeoPoint: loc)
query.limit = 100
query.whereKey("showMe", equalTo: true)
query.findObjectsInBackgroundWithBlock { (objects, error : NSError!) -> Void in
if error == nil
{
self.objects = objects as [PFObject]
}
} //returns nothing
var query = PFQuery(className: "resorts")
query.whereKey("geoPoint", nearGeoPoint: loc)
query.limit = 100
query.whereKey("showMe", equalTo: true)
query.findObjectsInBackgroundWithBlock { (objects, error : NSError!) -> Void in
if error == nil
{
self.objects = objects as [PFObject]
}
} //returns objects
try this
var myList = [AnyObject]()
query.findObjectsInBackgroundWithBlock{(object:[AnyObject]!, error = NSError! ) -> Void in
if error == nil {
println("successful query")
for object in objects {
self.myList.append(object)
}
} else {
println(error)
}
}