Retrieve User info from Parse - swift

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"]

Related

How to make app automatically recognise current user Firestore document ID when signed in?

When a user is signed up through my form, a document gets created associated with that user. My main goal is to create a global function that can recognize the user that is signed in and get their document ID. I have a function setup for adding documents to a subcollection of the user document which is perfectly setup, the only downfall is that when I'm testing with multiple accounts, I have to manually switch the collection path. Here is what I mean.
#IBAction public func createEventButton(_ sender: UIButton) {
let error = validateFields()
if error != nil {
showError(error!)
} else {
db.collection("school_users/\(stThomas)/events").addDocument(data: ["event_name": nameTextField.text, "event_date": dateTextField.text, "event_cost": costTextField.text, "for_grades": gradesTextField.text]) { (error) in
if error != nil {
self.showError("There was an error trying to add user data to the system.")
} else {
self.dismiss(animated: true, completion: nil)
}
}
}
So as you can see here, I am using string interpolation with the "stThomas" constant I used to store a document ID. I basically want to create a function that will recognize the document ID of the user signed in so I can use my Constants instead of string interpolation and having to manually switch the user collection path each time, which would be eventually impossible during production.
Not to mention, I do have a function to grab the document ID, say for instance an event is clicked, but as a beginner in Swift, I can't seem to connect the dots. I will also show this function for clarification.
func getDocID() {
db.collection("school_users/\(notreDame)/events").getDocuments() { (querySnapshot, error) in
if let error = error {
print("There was an error getting the documents: \(error)")
} else {
self.documentsID = querySnapshot!.documents.map { document in
return DocID(docID: (document.documentID))
}
self.tableView.reloadData()
}
}
}
And in this function you can see my other constant "notreDame" with another stored document ID. If anybody knows a simple way to do this that would be great. And yes, I checked the Firebase documents, thank you for asking.
I've did some extra research and realized that I can use User IDs in collection paths. My problem is now solved. Many more problems to come though.

Relational query on PFObject

I have a PFObject, Account that contains an array of Users which are subclasses of PFUserss. The User then has a NSDictonary property, allowableApps, that's a NSDictionary of arrays, where they arrays contain PFObjects.
So as a structure:
Account
var users: [User]
which points to....
User
// Each key is an array of AllowApp
var allowableApps: NSMutableDictionary
which points to...
AllowableApp
var appName: String
var appURL: String
var isAllowed: Bool
I'm trying to fetch all of these relations down to AllowableApp in a single query. I've tried using the .includeKey like this:
accountQuery?.includeKey("users")
accountQuery?.includeKey("allowableApps")
which didn't work. I've also tried:
accountQuery?.includeKey("users.allowableApps.appName")
accountQuery?.includeKey("users.allowableApps.appURL")
accountQuery?.includeKey("users.allowableApps.isAllowed")
I try to populate a UITableView with all the AllowableApp objects but I get this error:
Key "appName" has no data. Call fetchIfNeeded before getting its value.
Which I understand, I need to fetch all of them before trying to access the appName property. (which I'm trying to set cellForRowAtIndexPath).
Here is my full query:
let currentUser = User.currentUser()
let accountQuery = Account.query()
accountQuery?.whereKey("primaryUser", equalTo: currentUser!)
accountQuery?.includeKey("users.allowableApps")
accountQuery?.getFirstObjectInBackgroundWithBlock({ (account, error) in
if (error != nil) {
completion(users: nil, error: error)
}
else {
let users = (account as? Account)!.users
completion(users: users, error: nil)
}
})
My thought right now is to just loop through all of the AllowableApp objects in viewDidAppear calling fetchInBackgroundWithBlock. Then once they are all loaded I reload the table data.
This seems realllly messy and a common problem. Is there a more elegant solution that I'm just not seeing?
From what i understand you have the following structure:
Account
Users (Array of User)
AllowsableApps (Array of AllowApps)
First of all change the NSMutableDictionary to Array. NSMutableDictionary is a key-value pairs and in parse you should create one field. So you can use Array of AllowApps and it will do the same effect.
In order to fetch all accounts and users in each of the account and allowable apps per user you need to build the following query:
// You can do it with sub classing if you want
let query = PFQuery(className: "Account")
query.includeKey("users.allowableApps")
query.findObjectsInBackgroundWithBlock {
(objects: [PFObject]?, error: NSError?) -> Void in
}
Now for your users array. If your users array is users that needs to login the app it's better to inherit from PFUser and not from PFObject because PFUser contains all the logic for handling users in your app.

Querying for Relation Data in a PFQuery Table View Controller in Swift

I am trying to retrieve the the current user's friends by accessing the "friends" column in Parse. The way I set the friends up is by having the user select users in another view that are then added to a Relation called "friends" in their User row in Parse. I can get the users to save as a Relation in Parse but I can't figure out how to actually get those Relationed Users to show up in the Friends Table View. Here is my current code:
override func queryForTable() -> PFQuery {
let currentuser = PFUser.currentUser()
// Start the query object
let query = PFQuery(className: "_User")
// Add a where clause if there is a search criteria
if FriendSearch.text != "" {
query.whereKey("username", containsString: FriendSearch.text)
}
// Order the results
query.orderByDescending("score")
// Return the query object
return query
}
How do I get the current user's related users to appear in the PFTable View Controller? Thanks
You don't create a new query (particularly using the private class name for users). Instead you get the relation from the user and ask the relation for its query. Once you have that you can add additional parameters to it and return it.
I figured out what I did wrong. I needed to make a value for the relation in the current user, then make that a query.
// Define the query that will provide the data for the table view
override func queryForTable() -> PFQuery {
**let currentuser = PFUser.currentUser()?.relationForKey("friends")
// Start the query object
let query = currentuser?.query()**
// Add a where clause if there is a search criteria
if FriendSearch.text != "" {
query!.whereKey("username", containsString: FriendSearch.text)
}
// Order the results
query!.orderByDescending("score")
// Return the qwuery object
return query!
}

How do you store a dictionary on Parse using swift?

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.

How to access custom user table columns from Parse.com

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!