Chris Hardaker
Chris Hardaker

Reputation: 105

NSURLConnection returns data but I cannot read it

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

Upvotes: 2

Views: 5266

Answers (4)

Radix
Radix

Reputation: 3657

You need to convert the NSMutableData received by the NSURLConnection delegate method to readable NSString by using the below code

 NSString *finalString = [[NSString alloc]initWithData:responseData encoding:NSUTF8StringEncoding];

and that should do it.

Upvotes: 1

Aliaksandr Andrashuk
Aliaksandr Andrashuk

Reputation: 965

You need work with your data in:

- (void)connectionDidFinishLoading:(NSURLConnection *)connection;

Because

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data;

can be called many times

You can do that:

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
    [myData appendData:data];
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
    // TODO: work with data
}

NSMutableData* myData must be instance var.

Upvotes: 1

Allamaprabhu
Allamaprabhu

Reputation: 865

Try with other encoding..May be ASCII encoding instead of UTF-8..It may work out

Upvotes: 0

Manuel
Manuel

Reputation: 10303

if you want to change the data into an NSString you can do this:

NSString *responsestring = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding];
NSLog(@"%@", responsestring);

Upvotes: 5

Related Questions