parse.com swift - does not have a member getUserObjectWithId - swift

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

Related

Store every username in the firebase database into an array variable?

Im trying to build a social media app and I have the design down and Ive been up all night trying to figure this out with no luck. I'm fairly new to coding so any help would be appreciated! Thank You! (Also my apologies if this question is already asked. Ive tried looking everywhere and couldn't find anything)
Well to start off you need to create variable which will be database reference and array where the data will be stored such as:
var Array = [String]() //array of strings (usernames)
var ref : DatabaseReference! //define type of variable
then you assign it in viewDidLoad:
ref = Database.database().reference()
using this you'll be able to access your database and load current users:
ref.child("data").observeSingleEvent(of: .value, with: { (snapshot) in
guard let value = snapshot.value as? NSDictionary else {
self.listIsEmpty()
print("The user has no data in the database")
return
}
let userItem = value["Username"] as? [String] //loads the data
self.Array = userItem! //saves data to array
and then finally to write data you start by appending array which we have:
Array.append(textField.text) //reference textfield where username is or variable
ref.child("data").setValue(["Username":self.Array])

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.

Retrieve User info from Parse

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

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!