我正在关注以下问题和教程:
但是我仍然缺少一些东西。我的委托方法
- (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");
}
我怀疑确实没有返回任何数据(由于某些Web服务错误或请求准备不正确)。
如果愿意,您可以使用Charles观察请求和响应以确认这一点。BTW,Charles或任何类似的工具,都是添加到您的武器库中的有用武器,因为它大大简化了诊断HTTP问题的过程,将与网络相关的问题与客户端编程问题隔离开来。
无论如何,如果遇到此类错误,statusCode
服务器通常会返回非200的错误。请参阅HTTP状态代码列表。
您还可以通过实现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);
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句