How should I access columns that I've added to the User table when I have a currentUser object?
I have a PFUser.currentUser() and I want to access the nickname column that I added via the web interface.
Can I use the currentUser to get the data e.g.:
var nickname = PFUser.currentUser()["nickname"] as String
Or do I have to use a user query? e.g.:
var query = PFUser.query()
query.whereKey("username", equalTo:PFUser.currentUser().username)
var user = query.findObjects().first as PFUser
var nickname = user["nickname"]
If you added date to the column locally, then you have to use the first way as you wrote, or if you added date in the browser, or uploaded to parse.com some way, you have to use the second way.
I would like to give my two cents too. First of all, Daniel was right in saying that if you added the date in the browser or uploaded it to parse.com, you need to use the second way. This is an updated answer with iOS 9 and Xcode 7.2:
var query = PFUser.query()
query!.whereKey("username", equalTo:PFUser.currentUser()!.username!)
do {
user = try query!.findObjects().first as! PFUser
} catch {
print("Error finding user")
}
if user?["rankNumber"] as? Int == nil {
user!["rankNumber"] = 0
user!.saveInBackground()
} else {
print(user!["rankNumber"] as! Int)
}
If I did it any other way, xcode would give me an error saying "failing to unwrap optional". I hope this can help someone!
Related
I have a second class in parse where each row is linked to the user and stores an int number. This is already setup.
Now I want to check for the current user and get the int that is saved and put that in a label. Any Ideas?
you will need to query with constraints ("meaning that get data only for the currentUser"). Then you have two options to retrieve their data either use getfirstobjectinbackgroundwithblock() method which will get at least one row of data from parse. Or use findObjectsInBackgroundWithBlock() method which will return multiple rows from parse.
if in parse, the user is being saved as pointer use that line:
let userT = PFUser.CurrentUser() //<-- to get CurrentUser
if in parse, the user is being saved as string use that line
let userT = PFUser.CurrentUser().username //<-- to get CurrentUser
In this code, I use the getFirstObjectInBackgroundWithBlock method because I think you are only displaying one thing for the user, So if I am wrong use the second method findObjectsInBackgroundWithBlock
let query = PFQuery(className:"whateverNameYourClassIs")
let userT = PFUser.CurrentUser() //<-- to get CurrentUser
query.whereKey("NameOfUserColummInParse" equalTo:userT!)
query.getFirstObjectInBackgroundWithBlock { (object: PFObject?, error: NSError?) -> Void in
if error == nil
{
if let retreiveObject = object
{
let data = retreiveObject["IntValue"] as! Int //<-- IntValue supposed to be the name of your class column in parse where you want to retrieve the value.
}
}
})
I am coding an app and have user upon the user logging in I would like to take them to their dashboard and display info regarding their account. I am trying to display the username in a label but am having issues retrieving it. I am using the following code:
func getData(){
var query: PFQuery = PFQuery(className: "User")
query.whereKey("username", equalTo: "actualUsername")
query.getFirstObjectInBackgroundWithBlock{
(object: PFObject!, error: NSError!) - >Void; in
if object != nil {
NSLog("Success!")
} else {
NSLog("something went wrong")
}
}
I am using swift and xcode7
You can use the currentUser property of the PFUser object. This returns the informations about the user who is currently logged in. Then you can access the username etc:
PFUser.currentUser.username
Your problem is that the class you're querying, "User", doesn't exist. It's actually "_User", though it is more proper to use var query : PFQuery = PFUser.query() (see this answer)
Christian isn't wrong, though. If you have a user signed in, PFUser.currentUser returns the current user. So create a user PFUser variable and assign PFUser.currentUser to it, then you can access the elements using user["username"]
I am very new to swift and I don't know Obj C at all so many of the resources are hard to understand. Basically I'm trying to populate the dictionary with PFUsers from my query and then set PFUser["friends"] to this dictionary. Simply put I want a friends list in my PFUser class, where each friend is a PFUser and a string.
Thanks!
var user = PFUser()
var friendsPFUser:[PFUser] = []
var friendListDict: [PFUser:String] = Dictionary()
var query = PFUser.query()
query!.findObjectsInBackgroundWithBlock {
(users: [AnyObject]?, error: NSError?) -> Void in
if error == nil {
// The find succeeded.
println("Successfully retrieved \(users!.count) users.")
// Do something with the found objects
if let users = users as? [PFUser] {
friendsPFUser = users
for user in friendsPFUser{
friendListDict[user] = "confirmed"
}
user["friends"] = friendListDict //this line breaks things
user.saveInBackground()
}
} else {
// Log details of the failure
println("Error: \(error!) \(error!.userInfo!)")
}
}
To be clear, this code compiles but when I add
user["friends"] = friendListDict
my app crashes.
For those who might have this issues with. "NSInternalInconsistencyException" with reason "PFObject contains container item that isn't cached."
Adding Objects to a user (such as arrays or dictionaries) for security reasons on Parse, the user for such field that will be modified must be the current user.
Try signing up and using addObject inside the block and don't forget do save it!
It helped for a similar problem I had.
I need to save an object into Parse with pointer to User table.
At first I try to get PFUser object by objectId
var query = PFUser.query()
var user = query.getUserObjectWithId(a.id)
or try that
var user = PFUser.getUserObjectWithId(a.id)
and got the mistake "does not have a member getUserObjectWithId"
Parse API:
+ (PFUser *)getUserObjectWithId:(NSString *)objectId
And one more question. Is there a simple way to put the pointer to User table without an additional query?
I've try to save earlier PFUser object from query
var query = PFUser.query()
query.whereKey("email", equalTo:friendMail)
var friend = query.findObjects()
but the result of query is not PFUser.
The answer at the second question:
The object could be saved as PFUser as
friend = object as? PFUser
I just went through this issue for myself. Try this:
var user = PFQuery.getUserObjectWithId(a.id)!
In my own project, I was able to use the following successfully:
let sampleId:String = "abcXYZ"
let sampleUser:PFUser = PFQuery.getUserObjectWithId(sampleId)!
I am setting an app in which a user could create records. Let's say he/she is the owner of a chatroom. Therefore there is an attribute called "admin" in the chatroom record. This attribute takes a reference which is the ID of the owner.
Here is what I tried:
CKContainer.defaultContainer().fetchUserRecordIDWithCompletionHandler({
userRecordID, error in
if error != nil {
println("caca")
} else {
println("gettin close")
let UserRecordIDToStore = NSKeyedArchiver.archivedDataWithRootObject(userRecordID)
let iDString = userRecordID.recordName as String
daMainUser.setObject(iDString, forKey: "user")
}
})
When I pass iDString as above, and I create the record (the room), its admin reference is empty. Whether I did cast iDString as a String or not.
When I pass userRecordID directly, I get an error:
'CKRecordID' is not identical to 'CKRecordValue'
I have been looking everywhere but I cannot find more information about this.
Any help would be greatly appreciated. Thank you guys!
If your user field is set up as a CKReference field, then you should set it like this:
daMainUser.setObject(CKReference(recordID: userRecordID, action: CKReferenceAction.None), forKey: "user")
In your case you do not have to create a recordID because you already have it. Otherwise you had to create it with something like:
var recordID = CKRecordID(recordName: userRecordID.recordName)