I am trying to get an array of PFObjects, [PFObject], from Parse and seeing the issue below. What am I missing?
Error is Missing argument for parameter #1 in call
func loadData() {
rooms = [PFObject]()
users = [PFUser] ()
self.tableView.reloadData()
let pred = NSPredicate(format: "user1 = %# OR user2 = %#", PFUser.currentUser()!, PFUser.currentUser()!)
let roomQuery = PFQuery(className: "Rooms", predicate: pred)
//gives us all the information - includeKey all columns for the user class itself
roomQuery.includeKey("user1")
roomQuery.includeKey("user2")
roomQuery.findObjectsInBackgroundWithTarget{ (results: [AnyObject]!, error: NSError!) -> Void in
if error == nil {
self.rooms = results as [PFObject]
for room in self.rooms {
let user1 = room.objectForKey("user1") as PFUser
let user2 = room.objectForKey("user2") as PFUser
if user1.objectId != PFUser.currentUser() {
self.users.append(user1)
}
if user2.objectId != PFUser.currentUser() {
self.users.append(user2)
}
}
self.tableView.reloadData()
}
}
}
Error:
It seems that you want to handle the response with a block but you decided to use findObjectsInBackgroundWithTarget. You should go with findObjectsInBackgroundWithBlock:. So you should be having something like this:
roomQuery.findObjectsInBackgroundWithBlock {(objects: [AnyObject]?, error: NSError?) -> Void in
Related
I want to retrieve the user score from Parse and assign it to a variable. This function returns 0 before the query finishes. I have found a similar answer at Retrieve object from parse.com and wait with return until data is retrieved. However, I expect the function have a return value and what argument should I use for the completionhandler when calling this function. Any help would be appreciated, thanks!
Here is my code
func loadCurrentUserData() -> Int {
let query = PFQuery(className: "userScore")
let userId = PFUser.currentUser()!
var currentUserScore: Int = 0
query.whereKey("user", equalTo: userId)
query.findObjectsInBackgroundWithBlock {
(objects: [PFObject]?, error: NSError?) -> Void in
if error == nil {
let scoreReceived = objects![0]["score"] as! Int
currentUserScore = scoreReceived
dispatch_async(dispatch_get_main_queue(), { () -> Void in
self.userScore.text = "\(scoreReceived)"
})
} else {
print("Error: \(error!) \(error!.userInfo)")
}
}
return currentUserScore
}
The way you have set this function will not work as the query method is asynchronous. This can be fixed in two ways:
1) Use the PFQuery synchronous category:
http://parse.com/docs/ios/api/Categories/PFQuery(Synchronous).html
The only disadvantage to this approach is that the method will become blocking so make sure to call it from a background thread.
2) Restructure the function to use a completion block instead of a return value..i.e:
func loadCurrentUserData(completion: (score: Int!, error: NSError?) ->()) {
let query = PFQuery(className: "userScore")
let userId = PFUser.currentUser()!
var currentUserScore: Int = 0
query.whereKey("user", equalTo: userId)
query.findObjectsInBackgroundWithBlock {
(objects: [PFObject]?, error: NSError?) -> Void in
if error == nil {
let scoreReceived = objects![0]["score"] as! Int
currentUserScore = scoreReceived
dispatch_async(dispatch_get_main_queue(), { () -> Void in
self.userScore.text = "\(scoreReceived)"
})
completion(score: currentUserScore, error: nil);
} else {
print("Error: \(error!) \(error!.userInfo)")
}
completion(score: currentUserScore, error: error);
}
}
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()
In the user class I have a pointer "Friendship" to the user class, but when I run the program I get the error -
EDIT: I have figured out why I get the error. "Frinendship is not a pointer, it is a PFRelation, but I still want to access the ProPic and username. How would I do this?
Below is the user class
Below is the Pointer to the user class.
func getFriendPic(){
let imagequery = PFQuery(className: "_User")
imagequery.whereKey("username", equalTo: PFUser.currentUser()!)
imagequery.includeKey("Friendship")
imagequery.findObjectsInBackgroundWithBlock {( objects: [AnyObject]?, error: NSError?) -> Void in
for object in objects!{
let userPic = object["ProPic"] as! PFFile
userPic.getDataInBackgroundWithBlock({ (imageData: NSData?, error: NSError?) -> Void in
if(error == nil){
let image = UIImage(data: imageData!)
self.arrayOfFriends.append(image!)
print(self.arrayOfFriends)
}
// dispatch_async(dispatch_get_main_queue()) {
// self.collectionView.reloadData()
// }
})
}
}
}
func getFriendName(){
var query = PFQuery(className: "_User")
query.whereKey("username", equalTo: PFUser.currentUser()!)
query.includeKey("Friendship")
query.findObjectsInBackgroundWithBlock({
(objects: [AnyObject]?, error: NSError?) -> Void in
var objectIDs = objects as! [PFObject]
for i in 0...objectIDs.count-1{
self.arrayOfFriendsNames.append(objectIDs[i].valueForKey("username") as! String)
print(self.arrayOfFriendsNames)
}
})
}
The include query parameter doesn't work with Relation. Once you retrieved your user, you need to execute a second query to get the Friendship.
Here's an example to retrieve a PFRelation:
var relation = user.relationForKey("Friendship")
relation.query().findObjectsInBackgroundWithBlock {
(objects: [PFObject]?, error: NSError?) -> Void in
if let error = error {
// There was an error
} else {
// objects contains the friendships of the user
}
}
I tried this:
var data:NSMutableArray = NSMutableArray()
func loadData() {
var userQuery = PFUser.query()!
userQuery.whereKey("objectId", equalTo: PFUser.currentUser()!.objectId!)
userQuery.findObjectsInBackgroundWithBlock { (objects, error) -> Void in
if let objects = objects {
for object in objects {
self.data.addObject(object)
}
}
}
println(data) // this gives an empty NSMutableArray.
}
Is there any other way to get the data of current user? , I am doing this to make the profile Screen of the current user..Thanks for your time..
Use this to access the current user
if PFUser.currentUser() != nil {
PFUser.currentUser()!.fetchIfNeededInBackgroundWithBlock({ (user: PFObject?, error: NSError?) -> Void in
if user != nil {
var u = user as! PFUser
//Access the fetched user HERE
}
})
//NOT here, it will be nil here
}
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)
}
}