私はiOSの世界のもう一人の初心者であり、NSURLConnectionがデリゲートでどのように機能するかを理解しようとしています。私はあまり運がありません。ネットでいくつかの例を調べた後、次のテスト クラスを作成しました。私が抱えている問題は、どのデリゲート メソッドも呼び出されないことです。タイムアウト ループが存在し、トレース メッセージが表示されません。これを tcpmon で実行したところ、要求が送信され、応答が返されていることがわかりますが、デリゲートには何も配信されません。
誰が私が間違っているのか教えてもらえますか。
ありがとう。
これが私のコードです:
TestRequest.h
#import <Foundation/Foundation.h>
@interface TestRequester : NSObject <NSURLConnectionDataDelegate>
@property BOOL finished;
-(void)testRequest;
@end
そして実装:
#import "TestRequester.h"
@implementation TestRequester
-(void)testRequest {
NSString *url = @"<your favourite URL>";
NSMutableURLRequest *theRequest=[NSMutableURLRequest requestWithURL:[NSURL URLWithString:url]
cachePolicy:NSURLRequestReloadIgnoringLocalCacheData
timeoutInterval:60.0];
NSURLConnection *theConnection=[[NSURLConnection alloc] initWithRequest:theRequest delegate:self startImmediately:YES];
if (theConnection) {
NSLog(@"Connection created. Waiting....");
int count = 20;
while (!_finished && count-- > 0)
[NSThread sleepForTimeInterval:0.5];
if (_finished)
NSLog(@"Request completed");
else
NSLog(@"Request did not complete");
} else {
NSLog(@"Connection was not created!");
}
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
NSLog(@"-------------> Received data");
}
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
NSLog(@"-------------> Received response");
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
NSLog(@"-------------> connectionDidFinishLoading");
_finished = YES;
}
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
NSLog(@"-------------> Received error");
_finished = YES;
}
@end