我是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发布于 2012-11-13 06:29:32
您需要在头中将connections委托设置为NSURLConnectionDelegate类型,而不是NSURLConnectionDataDelegate类型。据我所知。
@interface TestRequester : NSObject <NSURLConnectionDelegate>发布于 2012-11-13 06:48:20
看起来你的连接超出了作用域。您可能正在使用ARC。
TestRequest.h
#import <Foundation/Foundation.h>
@interface TestRequester : NSObject <NSURLConnectionDelegate>
{
NSURLConnection *theConnection;
}
@property BOOL finished;
-(void)testRequest;
@end
-(void)testRequest {
NSString *url = @"<your favourite URL>";
NSMutableURLRequest *theRequest=[NSMutableURLRequest requestWithURL:[NSURL URLWithString:url]
cachePolicy:NSURLRequestReloadIgnoringLocalCacheData
timeoutInterval:60.0];
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!");
}
}https://stackoverflow.com/questions/13352599
复制相似问题