我是iOS世界的另一個新手,一直試圖弄清楚NSURLConnection如何與它的委託一起工作。我沒有多少運氣。在網上查看幾個示例之後,我創建了以下測試課程。我遇到的問題是我的委託方法都沒有被調用過。我的超時循環存在一個沒有跟蹤消息是每一個顯示。我通過tcpmon運行了這個程序,可以看到請求發送出去,響應被髮送回去,但是沒有任何東西被傳送給我的代理。NSURLConnectionDelegate沒有被調用
誰能告訴我我做錯了什麼。
謝謝。
這裏是我的代碼:
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
請顯示調用此類的代碼。 –