ankur kumawat ankur kumawat - 21 days ago 5x
iOS Question

How to create login condition and core data table values can't be stored twice

I have some problem on my project. Login form of my mobile app attached to Php Login service and performing well too.I am also added core-data. In core data table, user id text field and password text field of login form and their data store in local DB, work properly.

But I want, when user login at the first time, then the values are stored in local database value store and when the user log out from here and second time user login with same login id and password at that time database cannot record twice.

Clearly, I want values can't be stored twice. please suggest mt how it works.

I am waiting for your reply.

Thanking you


- (IBAction)btn_action:(id)sender {
if([[self.tx_userid text] isEqualToString:@""] || [[self.tx_password text] isEqualToString:@""] ) {

else {

NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:@"MYURL"]];

//create the Method "GET" or "POST"
[request setHTTPMethod:@"POST"];

NSString *userUpdate =[NSString stringWithFormat:@"loginid=%@&loginpassword=%@",_tx_userid.text,_tx_password.text, nil];

//Check The Value what we passed
NSLog(@"the data Details is =%@", userUpdate);

//Convert the String to Data
NSData *data1 = [userUpdate dataUsingEncoding:NSUTF8StringEncoding];

//Apply the data to the body
[request setHTTPBody:data1];

//Create the response and Error
NSError *err;
NSURLResponse *response;

NSData *responseData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&err];

// if ([response statusCode] >= 200 && [response statusCode] < 300)

NSError *error = nil;
NSDictionary *jsonData = [NSJSONSerialization

int success = [jsonData[@"success"] integerValue];

if(success == 1)
// stored in local DB
NSManagedObjectContext *context = [self managedObjectContext];

NSManagedObject *newDevice = [NSEntityDescription insertNewObjectForEntityForName:@"Loginuser" inManagedObjectContext:context];

[newDevice setValue:self.tx_userid.text forKey:@"userid"];
[newDevice setValue:self.tx_password.text forKey:@"password"];

NSError *error = nil;
// Save the object to persistent store
if (![context save:&error]) {
NSLog(@"Can't Save! %@ %@", error, [error localizedDescription]);

NSLog(@"Login SUCCESS");
[self performSegueWithIdentifier:@"login_success" sender:self];
} else {

NSString *error_msg = (NSString *) jsonData[@"error_message"];
[self alertStatus:error_msg :@"Sign in Failed!" :0];



NSLog(@"app dir: %@",[[[NSFileManager defaultManager] URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask] lastObject]);


- (void) alertStatus:(NSString *)msg :(NSString *)title :(int) tag
UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:title
otherButtonTitles:nil, nil];
alertView.tag = tag;
[alertView show];


There are different solutions for your problem.

Solution 1: You can clear the user id and password from coredata whenever the user logs out. So when the user logs in next time, it won't add the same user id again. (I prefer this solution)

Solution 2: If you really don't want to clear the user id when the user logs out, you can check just before login whether the user id is already present in core data or not. If it's already there, you don't need to add it again. You can overwrite any parameter if you want (But I basically don't prefer this one because you don't need to save any details in coredata if you have a backend server and database to keep track of the users already logged in.)

Critical issue in your code: Don't save information like passwords in coredata as it lacks privacy. If you really want to save the password, you can save it in the keychain. Lot of third party classes are available which does that(Eg:


First, you need to fetch all the user ids from the coredata

AppDelegate *appDelegate =[[UIApplication sharedApplication]delegate];

NSManagedObjectContext *context = [appDelegate managedObjectContext];

NSFetchRequest *request = [[NSFetchRequest alloc]initWithEntityName:@"LoginUser"];

NSError *error = nil;

NSArray *results = [context executeFetchRequest:request error:&error];

if (error != nil) {

   NSLog(@"Coredata fetch failed");
else {
   BOOL userPresent = NO;
   for(NSManagedObject *user in results){
      if([[user objectForKey:@"userid"] isEqualToString:self.tx_userid.text])
         userPresent = YES;
   if(userPresent == YES)
     //user is present in DB
     //new user