Search code examples
phpiosasynchronousafnetworkingafnetworking-2

AFNetworking asynchronous POST request for username and password parameter (Objective-C iOS)


I am new to iOS Development and I am stuck in my small project where I have to create asynchronous POST request to the php website. I read resources online and found AFNetworking is best to do this work so I installed AFNetworking 2.4 using cocoapods through terminal. I have a view controller which has 2 textfields (Username and Password), Whenever I press Login button, I to send an asynchronous POST request to php website.The POST request must contain the parameters 'username' and 'password' and will receive a JSON response back with a 'code' and a 'message'. I have to display the parsed code and message in a UIAlert along with how long the api call took in miliseconds. The only valid login is username: Yomaki password:asdfgh. When a login is successful, tapping 'OK' on the UIAlert should bring us back to the MainMenuViewController. Please look at what I have tried code below. I have tried following couple tutorials online but didnt work.

Please look at the code below,

(IBAction)loginButton:(id)sender

{

    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    NSDictionary *parameters = @{@"Yomaki": _usernameTextField, @"asdfgh": _passwordTextField};

    NSURLRequest * request = [NSURLRequest requestWithURL:[NSURL URLWithString:@"PHP URL HERE"]];
    AFHTTPRequestOperation * operation = [[AFHTTPRequestOperation alloc] initWithRequest:request];

}

Please help me with the code since this is the first time I am sending asynchronous POST request to the php website.

Thanks in advance.


Solution

  • You don't want to use _usernameTextField (the UITextField), but rather _usernameTextField.text or, perhaps better, self.usernameTextField.text (the NSString property of that test field). The same is true with the password.

    I'd also avail yourself of the POST method:

    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    NSDictionary *parameters = @{@"userid": self.usernameTextField.text, @"password": self.passwordTextField.text};
    
    [manager POST:url parameters:parameters success:^(AFHTTPRequestOperation *operation, id responseObject) {
        NSLog(@"JSON: %@", responseObject);
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        NSLog(@"Error: %@", error);
    }];
    

    Note, in your dictionary, you're replaced the field names (presumably something like userid and password, though check with your web service authors) with what appear to be sample userid/password values. I think you want to restore the original field names.