I am using Parse as my backend for my app. Once the user logs into their account I am trying to get the next view to say "Welcome, (First Name)" at the top. However, I cannot seem to figure out how to accomplish this even using Parse's online documents. Their site directed me here for further assistance. I have tried using their query feature, but could not figure it out. In other words, I am trying to pull the current logged in user's first name, from the database and display it once logged in.
Current code:
PFQuery *query = [PFUser query];
[query whereKey:#"firstName" equalTo:currentUser]; // find user's first name
NSArray *firstName = [query findObjects];
Previous code:
PFUser *currentUser = [PFUser currentUser];
if (currentUser) {
// do stuff with the user
Welcome.text = [NSString stringWithFormat:#"Welcome,", currentUser];
Your overcomplicating things.
You don't have to execute a query every time the view loads, instead you should put this in a plist or NSUserDefaults as not to use an API request simply to display the current users name.
However, you can do the following to the current users username :
if ([PFUser currentUser]) {
Welcome.text = [NSString stringWithFormat:#"Welcome, %#", [PFUser currentUser].username];
}
First of all you should check if you actually sign-up and/or logged into Parse with this kind of function:
[PFUser signUpInBackgroundWithBlock:^(BOOL succeeded, NSError *error) {
}];
[PFUser logInWithUsernameInBackground:#"My username" password:#"My password" block:^(PFUser *validUser, NSError *error) {
}];
Check this link: https://parse.com/docs/ios_guide#users-signup/iOS
After you did this, whenever you you want to retrieve your user information,
[PFUser currentUser] is the right way to call some information:
Say for example you want to retrieve the objectId you can get it like this:
NSString *str = [PFUser currentUser].objectId;
Or say you want to set a custom value like this:
NSString *str = #"My custom object";
[PFUser setObject:str forKey:#"MyCustomObject"];
[PFUser saveInBackgroundWithBlock:^(BOOL succeeded, NSError *error) {
}];
Than you retrieve it like this:
NSString *str = [PFUser objectForKey:#"MyCustomObject"];
You should really check the documentation and example by Parse that are really well explained ! ;)
(Here are some tutorials/Examples by Parse: https://parse.com/tutorials)
How is the transition from your login to your main view set up? Are they both two different controllers?
If so, you should look into NSNotificationCenter...
In your MainViewController, implement
[[NSNotificationCenter defaultCenter] addObserver:self
selector:#selector(loadObjects)
name:#"loginFinished"
object:nil];
And loadObjects will be
- (void)loadObjects
{
Welcome.text = [NSString stringWithFormat:#"Welcome %#", [[PFUser currentUser] objectForKey:"userNameField"]];
}
* You need to parse the PFUser object to access its fields. Its just a dictionary so supply it a key 'username' or whatever, and you receive a value 'myusername'. *
Then in your LoginViewController, within your [PFUser logInWithUsernameInBackground:password:block
Implement this
[PFUser logInWithUsernameInBackground:#"My username" password:#"My password" block:^(PFUser *validUser, NSError *error) {
if (!error) {
[[NSNotificationCenter defaultCenter] postNotificationName:#"loginFinished" object:nil];
}
}];
But this is basically how you should setup your login->main flow. Learn NSNotifications, Delegation, and maybe KVO... Learning these will make you a understand how data can be passed around in the iOS/Mac environment.
Heres an analogy for all of them:
NSNotification: A teacher(NSNotification poster) announces a test to all his students(NSNotification observer), or at least the one's who are currently in class, students missing class aren't observing.
Delegate: A student finishes a test and informs the professor(delegate).
KVO: A student(KVO poster) completes a question and raises their hand where the teacher or even other students could be KVOs (key-value observers) and act on their action.
Related
I'm trying to delete the image connected to the current user from the imageOne column in Parse.com. From the user class.
PFQuery *query = [PFUser query];
[query selectKeys:#[#"imageOne"]];
[query getObjectInBackgroundWithId:[[PFUser currentUser] objectId] block:^(PFObject *object, NSError *error) {
if (!error) {
[object deleteInBackground];
}
}];
My code doesn't work and the console logs this error "User cannot be deleted unless they have been authenticated via logIn or signUp".
How can I fix this?
Seems like the problem comes from the fact that object (image) comes from the user class, am I right?
Why are you doing a query for all users and then doing the delete for just the current user, that's the worst possible way to structure the query (and most likely to fail).
If the current user isn't in the first 100 returned your above code would never find a match.
This sort of query should instead be done using getObjectInBackgroundWithId:block:, but in the case of the current user you already have the object, just do this:
[[PFUser currentUser] deleteInBackground];
If instead you just want to delete information in a column, use the following:
PFUser *currentUser = [PFUser currentUser];
[currentUser removeObjectForKey:#"imageOne"];
[currentUser saveInBackground];
I would like write a PFUser object by the currentUser, i've added the ACL based on the Parse developer guide, but i still get an error:
'User cannot be saved unless they have been authenticated via logIn or signUp'
_ My code:
PFQuery *query = [PFUser query];
[query whereKey:#"username" equalTo:self.bBo];
PFObject *friendData = [query getFirstObject];
PFUser *user = (PFUser *)friendData;
PFACL *userACL = [PFACL ACL];
user.ACL = userACL;
[userACL setWriteAccess:YES forUser:[PFUser currentUser]];
PFRelation *friendRelation = [user relationforKey:#"array"];
[friendRelation addObject:[PFUser currentUser]];
[user saveInBackgroundWithBlock:^(BOOL succeeded, NSError *error) {
if (error){
NSLog(#"Error %# %#", error, [error userInfo]);
}
}];
I think i did everything correct, so i can't figure out what can be the problem. So if you made earlier something like this or know where is the problem, i would really appreciate any suggestions.
For security reasons, Parse won't allow you to save any changes to a user that is not currently logged in.
If you want to be able to make and save changes to user, you need to use Cloud Code and the Master Key to get around this roadblock.
I have had multiple problems like this before, and every time I've been forced to use a workaround via Cloud Code.
Here's an example of a workaround I did for creating a friends relationship between two users:
[PFCloud callFunction:#"editUser" withParameters:#{#"userId": user.objectId}];
The above code statement is in xcode, and executes the function I have added to my Cloud Code file.
Then, here's what my Cloud Code file looks like:
Parse.Cloud.define('editUser', function(request, response) {
var userId = request.params.userId;
var User = Parse.Object.extend('_User'),
user = new User({ objectId: userId });
var currentUser = request.user;
var relation = user.relation("friendsRelation");
relation.add(currentUser);
Parse.Cloud.useMasterKey();
user.save().then(function(user) {
response.success(user);
}, function(error) {
response.error(error)
});
});
The above code uses the Master Key to save changes to both the currently logged in user, and to the user who's objectId was passed into this function.
Code details:
var relation
This is just a variable I'm creating to hold what the following fucntion returns:
user.relation("friendsRelation");
In the above function, "friendsRelation" is the name of my PFRelation key in Parse.
Now that we have a valid relation object contain in our variable called relation, we execute this function with an argument of our currentUser object.
After that, all that's left is saving everything. I don't program with javascript, but I was still able to come up with the above solution by looking at the Parse Cloud Code docs, and searching around on their support forums.
If you take my template from above, and make some small changes, then you should be able to easily accomplish what you need. You just have to jump through these extra hoops because the Parse SDK doesn't want a situation where someone can login and somehow make changes to another user's account, whether by their own fault or a developer's mistake.
EDIT:
Here is the code to add the relationship for the current user:
PFRelation *friendsRelation = [[PFUser currentUser]relationforKey:#"friendsRelation"];
PFUser *user = [self.parseUsers objectAtIndex:indexPath.row];
[friendsRelation addObject:user];
[currentUser saveInBackgroundWithBlock:^(BOOL succeeded, NSError *error) {
if (error) {
NSLog(#"%# %#", error, [error userInfo]);
}
}];
And then you can call the Cloud Code method right after:
[PFCloud callFunction:#"editUser" withParameters:#{
#"userId": user.objectId
}];
i have searched a lot but can find any thing about parse background jobs scheduling .i am new in parse please give me example how and where to implement background jobs with scheduler in parse as there is no example any where
You schedule background jobs in the dashboard. Not possible in code
To get detailed knowledge about parse you must go through its guide which is available at https://www.parse.com/docs/ios_guide#top/iOS
As per your question, most of the work occurs in background for parse, for e.g.
-if you want to update user detail you can use without completion block:
PFUser *user = [PFUser currentUser];
user [#"firstname"] = self.firstnameTextFeild.text;
[user saveInBackground];
-if you want to update user detail you can use with completion block:
PFUser *user = [PFUser currentUser];
user [#"firstname"] = self.firstnameTextFeild.text;
[user saveInBackgroundWithBlock:^(BOOL succeeded, NSError *error) {
//Do anything you want
}];
-if you want to update user detail even if you are offline:
PFUser *user = [PFUser currentUser];
[#"firstname"] = self.firstnameTextFeild.text;
[user saveEventually]; // This will update user as device gets online
I have set up a few Parse users, I have a button that they can click to link to fb or twitter. I want to check if they are already linked so I can have an alertview which tells the user they are already linked.
Any thoughts?
Parse provides a set of utils for this kind of thing, one part of which is:
+ (BOOL)isLinkedWithUser:(PFUser *)user
You can use PFQuery for this:
id loggedUser = ...; // Get your facebook/twitter user info after clicking login
PFQuery *query = [PFUser query];
[query whereKey:#"email" equalTo:loggedUser[#"email"]];
[query countObjectsInBackgroundWithBlock:^(int number, NSError *error) {
if(number > 0) {
// The user already exists
} else {
// No user exists with the email
}
}];
Source: Parse.com
Okay so the problem I'm having in one of my functions is when users are logging in through Facebook, and my app is checking wether or not their Facebook username already exists in our app (Parse.com) database.
If so, present a view controller (which is where I'm having a problem since this is in a NSObject) if not, simply write their facebook username to parse username string. Error I get is: No known class method for selector 'presentViewController:animated:completion'
Here is my code:
PFQuery *query = [PFUser query]; //1
[query whereKey:#"username" equalTo:me.username];//2
[query findObjectsInBackgroundWithBlock:^(NSArray *objects, NSError *error) {//4
if (!error) {
NSLog(#"Successfully retrieved: %#", objects);
if ([objects count] > 0)
{
// LOOKING TO PRESENT VIEW CONTROLLER HERE?
// TRIED:
// [self presentViewController:[#"RegisterUsername" animated:YES completion:nil];
} else {
[[PFUser currentUser] setObject:me.username forKey:#"username"];
}
} else {
NSString *errorString = [[error userInfo] objectForKey:#"error"];
NSLog(#"Error: %#", errorString);
}
}];
and since this is inheriting from NSObject, it won't allow me to use the presentViewController. Not sure what else to do from here. :-( This view controller was going to make them set a username before continuing with our app. This code is currently in a login function in a header Comms.h (NSOBJECT) for Facebook iOS SDK
NSObject does not declare the method presentViewController:. You'll need to add a UIViewController subclass to the window and then present from that. In the completion block of your dismissViewController you should remove the parent from the window.
Alternatively you could create a delegate protocol for checking the username and then notify a UIViewController of the need to either set the username internally or present a login view.