我正在关注这些问题和教程:
但我仍然缺少一些东西。我的委托方法
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
一直被调用,需要一点时间,我猜它是因为互联网速度,但方法
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData*)data
永远不会被召唤。我错过了什么?请帮帮我。
我的代码:
-(void)loadDataBase{
NSString *post = [NSString stringWithFormat:@"advnr=123"];
NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSString *postLength = [NSString stringWithFormat:@"%lu",(unsigned long)[postData length]];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setURL:[NSURL URLWithString:[NSString stringWithFormat:@"http://thewebsite.abc/interface.php"]]];
[request setHTTPMethod:@"POST"];
[request setValue:postLength forHTTPHeaderField:@"Content-Length"];
[request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
[request setHTTPBody:postData];
NSURLConnection *conn = [[NSURLConnection alloc]initWithRequest:request delegate:self];
//return @"";
}
#pragma mark -
#pragma mark NSURLConnection delegates
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData*)data {
NSLog(@"Success"); // never gets executed
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
NSLog(@"didFinished");
}
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
NSLog(@"FAILED");
}
答案 0 :(得分:0)
我怀疑确实没有返回数据(因为某些Web服务错误或准备不正确的请求)。
如果您愿意,可以使用Charles来观察请求和响应以确认这一点。 BTW,Charles或任何这样的工具都是添加到您的库中的有用武器,因为它极大地简化了诊断HTTP问题,将网络相关问题与客户端编程问题隔离开来。
无论如何,如果您遇到这些类型的错误,您通常会得到服务器返回的非200 statusCode
。请参阅list of HTTP status codes。
您可以通过实施didReceiveResponse
并检查响应的标头来验证这一点:
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse*)response {
if ([response isKindOfClass:[NSHTTPURLResponse class]]) {
int statusCode = [(NSHTTPURLResponse *)response statusCode];
if (statusCode != 200) {
NSLog(@"Status code = %ld; response = %@", (long)statusCode, response);
// handle this error however you'd like
}
}
// temporarily, you might even want to log the whole `response` regardless of the status code
NSLog(@"%s: %@", __PRETTY_FUNCTION__, response);
}