如何在Xcode中创建登录页面?

时间:2013-12-16 22:11:59

标签: iphone .net objective-c post

所以我正在创建一个登录页面。但我不确定我在这里缺少什么部分!每次我尝试登录时都说凭据无效....我打赌我对POST和GET方法感到困惑。

任何帮助将不胜感激!谢谢。 我的代码如下:

- (IBAction)login:(id)sender {

if ([userName.text isEqualToString:@""] || [password.text isEqualToString:@""]) {
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Oops!" message:@"Please fill in all the fields!" delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil, nil];
    [alert show];
    return;
}

   NSURL *url = [NSURL URLWithString:@"http://WEBSITEHERE/api/users/AuthenticateUser"];
   NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];


NSDictionary *params = @{@"userName": userName.text, @"password": password.text};
NSError *error;
NSData *data = [NSJSONSerialization dataWithJSONObject:params options:0 error:&error];

NSLog(@"PARAMS = %@", params);


[request setHTTPMethod:@"GET"];

[request setValue:@"text/plain" forHTTPHeaderField:@"Accept"];

[request setValue:@"application/json;charset=utf-8" forHTTPHeaderField:@"Content-Type"];

[request setHTTPBody:data];



NSURLResponse *response = nil;


NSData *dataURL = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
NSString *result = [[NSString alloc] initWithData:dataURL encoding:NSUTF8StringEncoding];


NSString *responseString = [[NSString alloc]initWithData:dataURL encoding:NSUTF8StringEncoding];



NSLog(@"RESULT = %@", responseString);


    if ([result isEqualToString:@"1"])
    {


        UIStoryboard *mainStoryboard=[UIStoryboard
                                      storyboardWithName:@"MainStoryboard" bundle:nil];

        Home *mainView=[mainStoryboard
                                          instantiateViewControllerWithIdentifier:@"mainView"];

        mainView.modalTransitionStyle=UIModalTransitionStyleCoverVertical;

        [self presentViewController:mainView animated:YES completion:nil];

    }else
    {
        // invalid information
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Oops!" message:@"You must have entered something wrong! Try again!" delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil, nil];
        [alert show];
        return;

    }
}

1 个答案:

答案 0 :(得分:1)

我不确定您的服务器是如何设置的,但这是我在我最近的一个应用程序中设置身份验证请求的方式:

NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@%@", kBaseServerURL, sAuthMethod]]];
[request setHTTPMethod:@"GET"];
[request setValue:_username forHTTPHeaderField:@"j_username"];
[request setValue:_password forHTTPHeaderField:@"j_password"];
[request setValue:@"application/json" forHTTPHeaderField:@"Accept"];
[request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];