This is another simple question who’se answer escapes me after a hour on Google…
A user is typing something into a text field and upon this field loosing focus, I launch an NSURLConnection….
NSString *usernameTry = [sender text];
NSLog(@"username field = %@",usernameTry);
NSString *content = [@"http://www.siebenware.de/Rhythm/user/checkusername.php?username=" stringByAppendingString:usernameTry];
content = [content stringByAddingPercentEscapesUsingEncoding:NSASCIIStringEncoding];
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:content] cachePolicy:NSURLRequestReloadIgnoringLocalCacheData timeoutInterval:5.0];
NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
[connection start];
NSLog(@"%@",content);
Then I wait for the response….
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
NSLog(@"Received Response");
if ([response isKindOfClass:[NSHTTPURLResponse class]]) {
NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *) response;
int status = [httpResponse statusCode];
if (!((status >= 200) && (status < 300))) {
NSLog(@"Connection failed with status %@", status);
[UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
}
}
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
[resultsData appendData:data];
NSString *resultsString = [[NSString alloc] initWithData:resultsData encoding:NSUTF8StringEncoding];
NSLog(@"received data %@ %i",resultsString,[resultsString length]);
if ([resultsString isEqualToString: @"FAIL"]){
NSLog(@"failed to retrieve data");
}else{
resultsObjects = [[resultsString componentsSeparatedByString:@":"] mutableCopy];
if([resultsObjects objectAtIndex:0]==@"usernamecheck"){
if ([resultsObjects objectAtIndex:1]==username.text) {
if ([resultsObjects objectAtIndex:2]==@"NG"){
//set the check marker to bad
[usernameVer setImage:[UIImage imageNamed:@"redcross.png"]];
}else{
//set the check market to good
[usernameVer setImage:[UIImage imageNamed:@"greentick.png"]];
}
}
}
}
}
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
NSLog([NSString stringWithFormat:@"Connection failed: %@", [error description]]);
UIAlertView *errorAlert = [[UIAlertView alloc] initWithTitle:@"Unable to retrieve data" message:[NSString stringWithFormat:@"Error code %i",[error code]] delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil];
}
I see the response arrive in didReceiveResponse and am getting 18 bytes of data (which is correct).
However didReceiveData says that the ‘data’ is null. I know I am missing something exceptionally simple, and I promise to kick myself once this is cleared up.
Regards
Chris H
if you want to change the data into an NSString you can do this: