как отправить имя пользователя и пароль с помощью поста на сервер в приложении iphone - PullRequest
2 голосов
/ 19 марта 2012

Я создаю приложение для входа в систему. Я хочу отправить имя пользователя и пароль на сервер для проверки того, как это сделать, я сделал разными способами, но не могу опубликовать.Я отправляю имя пользователя и пароль, но он не работает, если я даю php имя пользователя и пароль, он работает так, как это сделать в iphone, чтобы отправить через сообщение

NSString *post = [[NSString alloc] initWithFormat:@"UserName=%@&Password=%@",username,pass];
NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];

NSString *postLength = [NSString stringWithFormat:@"%d", [postData length]];  

NSURL *url = [NSURL URLWithString:@"http://www.celeritas-solutions.com/emrapp/connect.php?"];
NSMutableURLRequest *theRequest = [NSMutableURLRequest requestWithURL:url];
[theRequest setHTTPMethod:@"POST"];  
theRequest setValue:postLength forHTTPHeaderField:@"Content-Length"];  
[theRequest setHTTPBody:postData];      

NSURLConnection *theConnection = [[NSURLConnection alloc] initWithRequest:theRequest delegate:self];

if( theConnection )
{
    webData = [[NSMutableData data] retain];
}
else
{
    NSLog(@"Inside the else condition");
}

[nameInput resignFirstResponder];
[passInput resignFirstResponder];
nameInput.text = nil;
passInput.text = nil;

Ответы [ 3 ]

2 голосов
/ 19 марта 2012

// Отредактировал ваш код, попробуйте это может помочь вам.

 NSString *post = [[NSString alloc] initWithFormat:@"UserName=%@&Password=%@",username,pass];

 NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];  

 NSString *postLength = [NSString stringWithFormat:@"%d", [postData length]];  

 NSURL *url = [NSURL URLWithString:@"http://www.celeritas-solutions.com/emrapp/connect.php?"];
 NSMutableURLRequest *theRequest = [NSMutableURLRequest requestWithURL:url];
 [theRequest setHTTPMethod:@"POST"];  
 [theRequest setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
 theRequest setValue:postLength forHTTPHeaderField:@"Content-Length"];  
 [theRequest setHTTPBody:postData]; 
2 голосов
/ 30 сентября 2014
//when the user clicks login<action>    


     - (IBAction)signinClicked:(id)sender {
        NSInteger success = 0;
        @try {
            //to check if username and password feild are filled
            if([[self.txtUsername text] isEqualToString:@""] || [[self.txtPassword text] isEqualToString:@""] ) {

                [self alertStatus:@"Please enter Username and Password" :@"Sign in Failed!" :0];

            } else {
                NSString *post =[[NSString alloc] initWithFormat:@"username=%@&password=%@",[self.txtUsername text],[self.txtPassword text]];
                NSLog(@"PostData: %@",post);
                //post it to your url where your php file is saved for login
                NSURL *url=[NSURL URLWithString:@"http://xyz.rohandevelopment.com/new.php"];

                NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];

                NSString *postLength = [NSString stringWithFormat:@"%lu", (unsigned long)[postData length]];

                NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
                [request setURL:url];
                [request setHTTPMethod:@"POST"];
                [request setValue:postLength forHTTPHeaderField:@"Content-Length"];
                [request setValue:@"application/json" forHTTPHeaderField:@"Accept"];
                [request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
                [request setHTTPBody:postData];

                //[NSURLRequest setAllowsAnyHTTPSCertificate:YES forHost:[url host]];

                NSError *error = [[NSError alloc] init];
                NSHTTPURLResponse *response = nil;
                NSData *urlData=[NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];

                NSLog(@"Response code: %ld", (long)[response statusCode]);

                if ([response statusCode] >= 200 && [response statusCode] < 300)
                {
                    NSString *responseData = [[NSString alloc]initWithData:urlData encoding:NSUTF8StringEncoding];
                    NSLog(@"Response ==> %@", responseData);

                    NSError *error = nil;
                    NSDictionary *jsonData = [NSJSONSerialization
                                              JSONObjectWithData:urlData
                                              options:NSJSONReadingMutableContainers
                                              error:&error];

                    success = [jsonData[@"success"] integerValue];
                    NSLog(@"Success: %ld",(long)success);

                    if(success == 1)
                    {
                        NSLog(@"Login SUCCESS");
                    } else {

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

                } else {
                    //if (error) NSLog(@"Error: %@", error);
                    [self alertStatus:@"Please Check Your Connection" :@"Sign in Failed!" :0];
                }
            }
        }
        @catch (NSException * e) {
            NSLog(@"Exception: %@", e);
            [self alertStatus:@"Sign in Failed." :@"Error!" :0];
        }
        if (success) {
            [self performSegueWithIdentifier:@"login_success" sender:self];
                }

    }






    - (void) alertStatus:(NSString *)msg :(NSString *)title :(int) tag
    {
        UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:title
                                                            message:msg
                                                           delegate:self
                                                  cancelButtonTitle:@"Ok"
                                                  otherButtonTitles:nil, nil];
        alertView.tag = tag;
        [alertView show];
    }
1 голос
/ 19 марта 2012

Добавить следующий код после

[theRequest setHTTPBody:postData];

NSURLResponse *response;// = [[NSURLResponse alloc] init];

NSError *error;// = [[NSError alloc] init;

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

NSString *str=[[NSString alloc]initWithData:urlData encoding:NSUTF8StringEncoding];

NSLog(@"Login response: is %@",str);
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...