NSURLConnection返回数据,但我无法读取它

时间:2012-04-17 11:10:38

标签: iphone nsurlconnection

这是另一个简单的问题,在Google上一小时后,我们的答案会让我失望......

用户在文本字段中输入内容,并且在此字段失去焦点时,我启动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);

然后我等待回应......

- (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];

}

我看到响应到达didReceiveResponse并获得18个字节的数据(这是正确的)。

然而didReceiveData表示'data'为空。我知道我错过了一些非常简单的事情,而且我保证一旦这个问题得到解决就会自我解决。

此致 克里斯H

4 个答案:

答案 0 :(得分:5)

如果要将数据更改为NSString,可以执行以下操作:

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

答案 1 :(得分:1)

您需要使用以下数据处理数据:

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

因为

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

可以多次调用

你可以这样做:

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

NSMutableData * myData 必须是实例var。

答案 2 :(得分:1)

您需要使用以下代码将NSURLConnection委托方法接收的NSMutableData转换为可读的NSString

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

那应该这样做。

答案 3 :(得分:0)

尝试其他编码。可能是ASCII编码而不是UTF-8 ..它可能会用完