How to retrieve ObjectID after PFUser login? - ios

PFUser.logInWithUsernameInBackground(fullName.text, password: password.text) {
(user: PFUser!, error: NSError!) -> Void in
if user != nil {
self.loginButton.enabled = false
self.helpButton.enabled = false
self.objectID = self.PFUser.objectId
}
}
I need to the users objectID after they log in. I know how to retrieve the objectID for just a PFObject when when it comes to PFUser I get an error (on the last line of code above). How can I get the id?

You are using self.PFUser.objectId, but I think you mean the user that you get back from the completion block. So try:
self.objectID = user.objectId
in the last line.

You should use either user.objectId or PFUser.currentUser().objectId instead of self.PFUser.objectId:
self.objectID = user.objectId
self.objectID = PFUser.currentUser().objectId

Related

Swift parse check user entered input and refresh value

I am trying to check if user entered data matches object data in a class. Comparing works, but refreshing does not.
This is the code.
let query = PFQuery(className: "registeredCodes")
query.whereKey("code", equalTo: userCodeEnter.text!)
query.getFirstObjectInBackgroundWithBlock {
(object: PFObject?, error: NSError?) -> Void in
if error != nil || object == nil {
print("The getFirstObject request failed.")
} else {
// The find succeeded.
print("Successfully retrieved the object.")
let totalPoints = PFUser.currentUser()?["points"] as? Int
self.userPointsLabel.text = "Punkte: " + "\(totalPoints)"
}
}
After
let totalPoints = PFUser.currentUser()?["points"] as? Int
self.userPointsLabel.text = "Punkte: " + "\(totalPoints)"
It just puts an "optional" in front of the original number, but not the new one. It looks something like optional(5)
Your code is querying (pulling an object from the server, with some check) for the registeredCodes class. Then, when that's done, your code is using the PFUser.currentUser to do something. This is a different class. The query will not result in an update to the PFUser.currentUser.
If PFUser.currentUser is expected to have changed then you need to call refreshInBackgroundWithBlock: on it to get those updates so you can use them (they will be ready when the completion block is called.

How to create pointer to Parse PFUser from facebook ID

I'm doing a Facebook graph call to get friends of the user that are using my app. I get the facebook ID of the user's friends back from the graph call. Below is what I'm attempting to obtain from Parse with that ID, but's it's not getting all the users back, I believe since its an async call. How can I save an array of pointers of the user's fb friends that are using the app? Thanks in advance!!
graphConnection.addRequest(requestFriends, completionHandler: { (connection: FBSDKGraphRequestConnection!, result: AnyObject!, error: NSError!) -> Void in
if result.objectForKey("friends") != nil {
// parsing dictionary to get results
let firstDict = result.objectForKey("friends")
let dataArray = firstDict!.objectForKey("data")
let myFriendsUsingTheAppCount = dataArray!.count
print("\(myFriendsUsingTheAppCount)")
let friendsArray:NSMutableArray = []
for var i = 0; i < dataArray!.count; i++ {
let friend = dataArray![i]
let friendFbObjectID = friend.objectForKey("id")!
let query = PFUser.query()
query!.whereKey("facebookID", equalTo: friendFbObjectID)
query!.findObjectsInBackgroundWithBlock({ (objects, error) -> Void in
if error == nil {
// this is where I was going to save this specific user as a pointer
} else {
// some error
}
})
// this is saving just the friend's name/fb id to an array, but I want an array of pointers to the PFUser
friendsArray.addObject(friend)
}
} else {
// fb friends is nil
print("FB friends came back nil")
}
})
This could be simplified into a single query by using whereKey:containedIn:
let facebookIDs = dataArray.map { $0.objectForKey("id")! }
let query = PFUser.query()!
query.whereKey("facebookID", containedIn: facebookIDs)
The query will now contain all users whose facebook id is in the array passed to the query.
(swift syntax may be incorrect did not double check)

PFUser not unwrapped - swift

I'm beginning to learn swift with parse and i've run into this error:
"Value of optional type 'PFUser?' not unwrapped; did you mean to use '!' or '?'
I can't seem to get it to work...
PFFacebookUtils.logInWithPermissions(["public_profile",
"user_about_me", "user_birthday"], block: {
user, error in
if user == nil {
println("the user canceled fb login")
//add uialert
return
}
//new user
else if user.isNew {
println("user singed up through FB")
//get information from fb then save to parse
FBRequestConnection.startWithGraphPath("/me?fields=picture,first_name,birthday,gender", completionHandler: {
connection, result, error in
//print results
println(result)
//result dictionary about user
var r = result as NSDictionary
//prnt dictionary
println(NSDictionary)
//match parse column with what fb sends
user["firstName"] = r["first_name"]
user["gender"] = r["gender"]
//r = result, then key into using picture. Then key into url using the data
let pictureURL = ((r["picture"] as NSDictionary)["data"] as NSDictionary) ["url"] as String
Instead of using if user == nil {... you should really use
if let user = user {
// Login succeeded...
}
else {
// Login failed
}
The variable user will then be unwrapped inside the if let and you can continue using user the same way you are.
Here is explanation: What is an "unwrapped value" in Swift?
PFFacebookUtils.logInWithPermissions(["public_profile",
"user_about_me", "user_birthday"], block: {
user, error in
if user == nil {
println("the user canceled fb login")
//add uialert
return
}
//new user
else if user!.isNew {
println("user singed up through FB")
//get information from fb then save to parse
FBRequestConnection.startWithGraphPath("/me?fields=picture,first_name,birthday,gender", completionHandler: {
connection, result, error in
//print results
println(result)
//result dictionary about user
var r = result as NSDictionary
//prnt dictionary
println(NSDictionary)
//match parse column with what fb sends
user["firstName"] = r["first_name"]
user["gender"] = r["gender"]
//r = result, then key into using picture. Then key into url using the data
let pictureURL = ((r["picture"] as NSDictionary)["data"] as NSDictionary) ["url"] as String

Assigning PFUser with A PFObject Swift

How can I add a PFUser to a PFObject, here is my code now:
var gameScore = PFObject(className: "SiteLog-\(jobName.text)")
gameScore["TypeOfWorks"] = "\(typeOfWorks.text)"
gameScore["DateAndTime"] = "\(formattedDate)"
gameScore.saveInBackgroundWithBlock {
(success: Bool, error: NSError?) -> Void in
if (success) {
// The object has been saved.
println("sucessfully sent to parse!")
} else {
// There was a problem, check error.description
println("Error Sending to Parse = \(error)")
}
So how would I be able to assign a user to it, the user is already logged in so how can I assign this PFObject to the current user logged in!
I am using iOS Swift - Xcode 6.3.1
Thanks,
George Barlow
In Objective-C you can reference the logged in user by calling [PFUser currentUser], which should translate to Swift as PFUser.currentUser(). Say you have a column for gameScore called user, you can add this line of code before saving gameScore:
if let user = PFUser.currentUser(), username = user.username {
user["column-name-in-parse-data"] = username
}

How to preset Parse fields?

https://www.flickr.com/photos/dom497/16118311866/
Based off the picture linked above, here's the scenario: A user signs-up in my app and their data is added to Parse. How can I get ElginSupAccess to be preset to false?
I've tried using the following to update the field but apparently I cannot update an undefined field. (using Swift)
var query = PFQuery(className:"_User")
query.getObjectInBackgroundWithId(nameID) {
(update: PFObject!, error: NSError!) -> Void in
if error == nil {
update["elginSupAccess"] = false
update.saveEventually()
Dom,
In Parse the correct syntax of querying the user class is below, you don't query it by class name:
PFQuery *query = [PFUser query];
or for swift
var query = PFUser.query()
query.getObjectInBackgroundWithId("xWMyZEGZ") {
(update: PFObject!, error: NSError!) -> Void in
if error != nil {
NSLog("%#", error)
} else {
update["ElginSupAccess"] = false
}

Resources