Assigning PFUser with A PFObject Swift - ios

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
}

Related

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)

Add column to PFUser AFTER signup? Parse, Swift

I would like my user to add/edit details about their profile after they register with my app.
#IBAction func doneEditting(sender: AnyObject) {
self.completeEdit()
}
func completeEdit() {
var user = PFUser()
user["location"] = locationTextField.text
user.saveInBackgroundWithBlock {
(succeeded: Bool, error: NSError?) -> Void in
if let error = error {
let errorString = error.userInfo?["error"] as? NSString
println("failed")
} else {
self.performSegueWithIdentifier("Editted", sender: nil)
}
}
}
the breakpoint stops right at user.saveInBackgroundWithBlock. No of the docs show how to append new columns after the signup.
Thanks!
You are mentioning that the user should be able to edit their profile after they have registered. When registering a user with Parse using signUpInBackgroundWithBlock, then the Parse SDK will automatically create a PFUser for you.
In your provided code you are creating and saving a completely new PFUser instead of getting the one which is currently logged in. If you are not using the PFUser which is logged in, then you will get the following error at user.saveInBackgroundWithBlock (which you are also mentioning in your post):
User cannot be saved unless they are already signed up. Call signUp first
To fix this, you will need to change:
var user = PFUser()
To the following:
var user = PFUser.currentUser()!
The rest of your code (for example user["location"] = locationTextField.text) works fine and will dynamically/lazily add a new column to your User database (which is what you want).
Parse allows you to add columns to a class lazily, meaning that you can add a field to your PFObject and if it is not present in your Parse class, Parse will add that column for you.
Here's example how you would add a column via code:
// Add the new field to your object
yourObject["yourColumnName"] = yourValue
yourObject.saveInBackground()
You'll notice that Parse will create a new column named yourColumnName on their web portal.
reference from HERE.

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

Parse: How can I update all rows with the same key value

How can I update all rows with the same key value in a Parse class?
As my code, I think Parse would cost a lot of my money if there are 100 objects per user.
Is there any other way to do that?
let username = PFUser.currentUser()?.username
let objectQuery = PFQuery(className: "FriendList")
objectQuery.whereKey("username", equalTo: username!)
objectQuery.findObjectsInBackgroundWithBlock { (friendList:[AnyObject]?, error:NSError?) -> Void in
if let friendList = friendList as? [PFObject] {
for myInfo in friendList {
myInfo["contact"] = contact
myInfo["portrait"] = PFFile(data: portraitNSData)
myInfo["company"] = company
myInfo["position"] = position
myInfo.save() // create a request?
}
}
}
Form array of needed objects and than just
PFObject.saveAllInBackground(objectsArray)
Parse has a functions to object see to save many objects (see documentation here)
PFObject.saveAllInBackground(array, block: {
(succeeded: Bool, error: NSError!) -> Void in
if (error != nil) {
println("Error saving: \(error)")
}
})
Unfortunately the documentation is not update to Swift but you can see a list of the function in objective-c
saveAll:
saveAll:error:
saveAllInBackground:
saveAllInBackground:block:
It would be best to create a CloudCode function. Then call that function from iOS. It's not difficult, see their documentation here: Parse.com

How to retrieve ObjectID after PFUser login?

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

Resources