Search code examples
objective-cxcodeios9

How to set a default user in xcode7 with the help of objective c?


I'm trying to build and login and logout application, but not able to login please help me to set default user id and password through which i would be able go to the next page


Solution

  • You can try this code it will help you :

        -(void)login
        {
    
    
            NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
            NSURLSession *session = [NSURLSession sessionWithConfiguration:configuration delegate:self delegateQueue:nil];
            NSURL *url = [NSURL URLWithString:@"http://www.example.com/pm/api/login"];
            NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url
                                                                   cachePolicy:NSURLRequestUseProtocolCachePolicy
                                                               timeoutInterval:60.0];
    
          [request addValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
    
    
            [request addValue:@"*/*" forHTTPHeaderField:@"Accept"];
    
            [request setHTTPMethod:@"POST"];
    
            NSString *mapData = [NSString stringWithFormat:@"username=admin&password=123456&api_key=bf45c093e542f057c123ae7d6"];
    
               NSData *postData = [mapData dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
    
            [request setHTTPBody:postData];
    
    
            NSURLSessionDataTask *postDataTask = [session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
    
                if(error == nil)
                {
    
                    NSString * text = [[NSString alloc] initWithData: data encoding: NSUTF8StringEncoding];
    
    
                    NSError *error = nil;
                    NSDictionary *json = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error];
    
                    if(error!=nil)
                    {
                        NSLog(@"error = %@",error);
    
                    }
    
                    dispatch_async(dispatch_get_main_queue(), ^{
                        [self checkUserSuccessfulLogin:json];
                    });
                }
                else{
    
                    NSLog(@"Error : %@",error.description);
    
                }
    
    
            }];
    
    
            [postDataTask resume];
    
        }
        - (void)checkUserSuccessfulLogin:(id)json
        {
          //  NSError *error;
           NSDictionary *dictionary = (NSDictionary *)json;
    
    
            if ([[dictionary allKeys] containsObject:@"login"])
            {
                if ([[dictionary objectForKey:@"login"] boolValue])
                {
    
                    if(checkBoxSelected == YES)
                    {
                        NSUserDefaults *defaults=[NSUserDefaults standardUserDefaults];
                        NSString* textField1Text = usernameField.text;
                        [defaults setObject:textField1Text forKey:@"textField1Text"];
    
                        NSString *textField2Text = passwordField.text;
                        [defaults setObject:textField2Text forKey:@"textField2Text"];
                        [defaults synchronize];
                    }
                    NSString *strID = [[NSUserDefaults standardUserDefaults] stringForKey:@"textField1Text"];
                    NSString *strPWD = [[NSUserDefaults standardUserDefaults] stringForKey:@"textField2Text"];
    
                    [[NSUserDefaults standardUserDefaults] setValue:[dictionary objectForKey:@"user_id"] forKey:@"CurrentUserLoggedIn"];
                  NSString *strUser = [[NSUserDefaults standardUserDefaults] stringForKey:@"CurrentUserLoggedIn"];
    
                    [[NSUserDefaults standardUserDefaults]synchronize];
                    [self saveLoginFileToDocDir:dictionary];
    
    
                    ItemManagement *i = [[ItemManagement alloc]init];
                    [self.navigationController pushViewController:i animated:YES];
    
                }
                else
                {
                    NSLog(@"Unsuccessful, Try again.");
                    UIAlertView *alertLogin = [[UIAlertView alloc]initWithTitle:@"Error" message:@"Wrong Username Or Password" delegate:self cancelButtonTitle:@"cancel" otherButtonTitles:nil];
                    [alertLogin show];
                }
            }
        }
    
    
    
    
        - (void)saveLoginFileToDocDir:(NSDictionary *)dictionary
        {
            NSArray *pListpaths =NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask, YES);
            NSString *pListdocumentsDirectory = [pListpaths objectAtIndex:0];
            NSString *path = [pListdocumentsDirectory stringByAppendingPathComponent:@"Login.plist"];
    
            BOOL flag = [dictionary writeToFile:path atomically:true];
    
            if (flag)
            {
                NSLog(@"Saved");
            }
            else
            {
                NSLog(@"Not Saved");
            }
    
        }
    
        - (NSDictionary *)getLoginFileFromDocDir
        {
            NSArray*pListpaths =NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask,  YES);
            NSString*pListdocumentsDirectory = [pListpaths objectAtIndex:0];
            NSString *path = [pListdocumentsDirectory stringByAppendingPathComponent:@"Login.plist"];
    
            NSDictionary *dict = [NSDictionary dictionaryWithContentsOfFile:path];
    
            return dict;
        }
    
    
    -(void)checkboxSelected:(id)sender
    {
        checkBoxSelected = !checkBoxSelected;
        [checkbox setSelected:checkBoxSelected];
    
    
    }