如何在目标c的帮助下在xcode7中设置默认用户



我正在尝试构建、登录和注销应用程序,但无法登录。请帮助我设置默认的用户id和密码,通过它我可以进入下一页

您可以尝试此代码,它将帮助您:

    -(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];

}

要在应用程序中设置默认用户,可以使用下面的代码

在您的AppDelegate.m

if ([[NSUserDefaults standardUserDefaults]boolForKey:@"IsFirstTime"])
        {
            UIStoryboard *mainStoryboard = [UIStoryboard storyboardWithName:@"Main" bundle:nil];
            ViewController *vc = [mainStoryboard instantiateViewControllerWithIdentifier:@"ViewController"];
            self.window.rootViewController = vc;
        }
        else
        {
            [[NSUserDefaults standardUserDefaults]setBool:YES forKey:@"IsFirstTime"];
            [[NSUserDefaults standardUserDefaults]synchronize];
        }

然后#import您的AppDelegate.m类到您放置登录代码的类

AppDelegate *delegate;

- (void)viewDidLoad
{
    [super viewDidLoad];
    delegate  = (AppDelegate *)[[UIApplication sharedApplication]delegate];
}
    NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
    NSURLSession *session = [NSURLSession sessionWithConfiguration:configuration delegate:self delegateQueue:nil];
    NSURL *url = [NSURL URLWithString:@"http://43.252.88.251/jsonandroid/"];
    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])

            {
                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 *ItemManagement = [[ItemManagement alloc]init];
             [self.navigationController pushViewController:ItemManagement 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];*/
            UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"Title" message:@"Hello" preferredStyle:UIAlertControllerStyleAlert];

            UIAlertAction *cancelbutton = [UIAlertAction actionWithTitle:@"" style:UIAlertActionStyleCancel handler:nil];
            //UIAlertAction *oktext= [UIAlertAction actionWithTitle:oktext style:UIAlertActionStyleDefault handler:nil];
            [alert addAction:cancelbutton];
            //[alert addAction:oktext];
        }
    }



- (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;
}

最新更新