这是另一个简单的问题,在 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 说“数据”为空。我知道我遗漏了一些非常简单的东西,我保证一旦解决这个问题就会踢自己。
问候克里斯 H