I'm trying to hit a REST api to see if a user is valid. I know the connectionDidFinishLoading
runs, but I'm not sure how to check the response (xml). Please advise.
The signIn
function gets the ball rolling
- (IBAction)signIn:(id)sender;
{
[emailError setHidden:YES];
if([emailAddressTxt text] && [passwordTxt text]) {
// send user/pass to server for validation
if([self NSStringIsValidEmail:[emailAddressTxt text]]) {
NSString *post = [NSString stringWithFormat:@"Email=%@&Password=%@", emailAddressTxt.text, passwordTxt.text];
NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSString *postLength = [NSString stringWithFormat:@"%d", [postData length]];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setURL:[NSURL URLWithString:@"http://www.mySite.com/validate.php"]];
[request setHTTPMethod:@"POST"];
[request setValue:postLength forHTTPHeaderField:@"Content-Length"];
[request setHTTPBody:postData];
[NSURLConnection connectionWithRequest:request delegate:self];
}
} else {
// give error dialogue
[emailError setText:@"User not found"];
[emailError setHidden:NO];
}
}
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
//[signInData setLength:0];
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)d {
//[signInData appendData:d];
// updated to:
signInData = (NSMutableData *)d;
}
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
// Fail..
[emailError setText:@"Connection Error"];
[emailError setHidden:NO];
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
NSString *responseText = [[NSString alloc] initWithData:signInData encoding:NSUTF8StringEncoding];
NSLog(@"%@", @"check");
NSLog(@"%@", responseText);
}
// an example response would be:
// <string xmlns="http://thedomain.com/">invalid login</string>
Ordinarily to parse XML
you would use NSXMLParser
, but with a string response a simple as "<string xmlns="http://thedomain.com/">invalid login</string>
" I'm assuming that a valid login would look like this :"<string xmlns="http://thedomain.com/">valid login</string>
"
If that is the case you can simply look for a response which contains the string @"valid login"
but does not contain @"invalid login"
if (([responseText rangeOfString:@"invalid login"].location == NSNotFound) && ([responseText rangeOfString:@"valid login"].location != NSNotFound)){
// Congrats valid
}
If (even better) a successful response would be "<string xmlns="http://thedomain.com/">successful login</string>
" then the if statement becomes easier to follow.
if ([responseText rangeOfString:@"successful login"].location != NSNotFound){
// Congrats valid
}