[英]Why my delegate method never gets called?
我正在關注以下問題和教程:
但是我仍然缺少一些東西。 我的委托方法
- (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問題的過程,將與網絡相關的問題與客戶端編程問題隔離開來。
無論如何,如果遇到此類錯誤,則服務器通常會返回非200 statusCode
。 請參閱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);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.