the query findObjectsInBackground not working - ios

i have 3 classes, i need to retrieve data depending on some condition , i use this code :
let query = PFQuery(className: "RiderRequest")
query.whereKey("username", equalTo: (PFUser.current()?.username!)!)
query.findObjectsInBackground(block: { (objects, error) in
if let riderRequests = objects {
for riderRequest in riderRequests {
if let driverUsername = riderRequest["driverResponded"] {
let query3 = PFQuery(className: "User")
query3.whereKey("username", equalTo: driverUsername)
query3.findObjectsInBackground(block: { (objects, error) in
if let driverinfo = objects {
for driver in driverinfo {
print("driverobject=\(driver)")
}
}
})
but the className: "User" not working and cant get data from it , always the object is nil.

Another way to retrieve data from the User Class with PFQuery is using the following:
let query : PFQuery = PFQuery(className: "_User")

Parse User is a special Parse class and requires a different Query constructor.
Update your code to:
let query3 = PFUser.query()

Related

Retrieve username from Parse

I've been trying to retrieve the username for a certain user from a user object in Parse. One of the queries i tried to to that with looks like this:
let query = PFQuery(className: "User")
query.whereKey("objectId", equalTo: userId!)
query.findObjectsInBackgroundWithBlock{(objects:[PFObject]?, error: NSError?) -> Void in
if error == nil {
for object in objects! {
self.username.text = String(object["username"])
}
}
}
Is there another way to do this? I'm really new to working with Parse and I really haven't found a way to make this work yet..
When querying the user table, use PFUser.query() to construct your query rather than PFQuery(className: "User")
let query = PFUser.query()
query.whereKey("objectId",equalTo: userId!)
query.findFirstObjectInBackgroundWithBlock{(object,error)->Void in
if error == nil{
if let user = object as? PFUser{
self.username.text = user.username;
}
}
}

Parse query containedIn doesn't return any value

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()

query with two key get one object in parse using swift

I am using parse in my app and I want to satisfy the two query and return object without using orQueryWithSubqueries. Here my query to parse code:
func queryToParse(){
var queryForBlood = PFQuery(className: "Donors")
queryForBlood.whereKey("BloodGroup", equalTo: bloodGroupTextField.text)
var queryForCity = PFQuery(className: "Donors")
queryForCity.whereKey("City", equalTo: citySearchTextField.text)
var query = PFQuery.orQueryWithSubqueries([queryForCity,])
query.findObjectsInBackgroundWithBlock { (objects, error) -> Void in
if error == nil {
self.tableData = objects as NSArray
println(self.tableData)
self.tableView.reloadData()
}
else
{
println(error)
}
}
}
Instead of creating two separate PFQuery, then you just have to create one. You only need to create several PFQuery when you want to make an OR query.
Your code should look something like this:
func queryToParse(){
let query = PFQuery(className: "Donors").whereKey("BloodGroup", equalTo: bloodGroupTextField.text).whereKey("City", equalTo: citySearchTextField.text)
query.findObjectsInBackgroundWithBlock { (objects, error) -> Void in
...
}
}

Limiting Parse query without query.limit in Swift

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]

ios swift parse: orderByAscending ist getting ignored

When I run this query:
var query = PFQuery(className: "CardSet")
query.whereKey("user", equalTo: PFUser.currentUser())
query.includeKey("lesson")
query.orderByAscending("createdAt")
query.findObjectsInBackgroundWithBlock { (objects, error) -> Void in ........
The results are never sorted by data, in fact they are always sorted by objectId.
What is wrong in my query?
This is my data on parse, sorted by date
This is my output on the device, sorted by objectId...
Had the same issue. Try adding this to your above code in block, it worked for me:
let array:NSArray = self.queryobjectsArray.reverseObjectEnumerator().allObjects
self.queryobjectsArray = NSMutableArray(array: array)
This whole issue ended quite strange...
What I did before, like in other views within the same project, I fetched the data from parse and pinned it to the local storage and called a second method to fetch the data from the local storage. This way I have fast reachable data from local storage and update it in the background for later use.
For some reason, the fetched data from online was sorted by date.
But the fetched data from the local pin was not and that was the reason, why my app displays the data in the wrong timeline.
I was not able to understand or solve this, but I helped myself by removing the local pinning and just grab the data from the internet.
I will show what the original process was:
var cardSetObjects: NSMutableArray! = NSMutableArray()
override func viewDidAppear(animated: Bool) {
self.fetchAllObjectsFromLocalDatastore()
self.fetchAllObjects()
}
func fetchAllObjectsFromLocalDatastore(){
var query = PFQuery(className: "CardSet")
query.fromLocalDatastore()
query.orderByDescending("createdAt")
query.findObjectsInBackgroundWithBlock { (objects, error) -> Void in
if (error == nil){
var temp: NSArray = objects as NSArray
self.cardSetObjects = temp.mutableCopy() as NSMutableArray
self.tableView.reloadData()
}else{
println(error.userInfo)
}
}
}
func fetchAllObjects(){
var query = PFQuery(className: "CardSet")
query.whereKey("user", equalTo: PFUser.currentUser())
query.includeKey("lesson")
query.orderByDescending("createdAt")
query.findObjectsInBackgroundWithBlock { (objects, error) -> Void in
if (error == nil) {
PFObject.pinAllInBackground(objects, withName:"CardSet", block: nil)
self.fetchAllObjectsFromLocalDatastore()
self.tableView.reloadData()
}else{
println(error.userInfo)
}
}
}
What I did at the end was to remove the fetchAllObjectsFromLocalDatastore method and put the data into the NSMutableArray right in fetchAllObjects.
But I still wonder why I had this sorting issue with this code...
Maybe someone will know...

Resources