我是 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