我完全按照this official documentation的指示完成了。我为测试目的创建了一个控制台项目。然后我创建了一个名为RequestSender的类(参见下面的代码),并在main函数中创建了这个类的实例。
RequestSender.h:
#import <Foundation/Foundation.h>
@interface RequestSender : NSObject <NSURLConnectionDelegate> {
NSMutableData* d;
}
@end
RequestSender.m:
#import "RequestSender.h"
@implementation RequestSender
- (id)init {
self = [super init];
if (self) {
NSString* s = @"http://www.apple.com/";
NSURL* u = [[NSURL alloc] initWithString:s];
NSURLRequest* r = [[NSURLRequest alloc] initWithURL:u];
NSURLConnection* c = [[NSURLConnection alloc] initWithRequest:r delegate:self];
if (c) {
d = [NSMutableData data];
}
return self;
} else {
return nil;
}
}
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
[d setLength:0];
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
[d appendData:data];
}
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
}
@end
毫无疑问,这将在主线程和默认运行循环中执行。但是,不调用委托方法。
我做了很多测试并阅读了很多帖子,但我仍然没有线索。
请帮帮我。这让我很生气。 感谢名单!
答案 0 :(得分:0)
我相信你错过了开始连接的部分。连接类为此提供了另一种方法,或者您可以从“c”对象中调用它。
NSURLConnection* c = [[NSURLConnection alloc] initWithRequest:r delegate:self];
if (c) {
d = [NSMutableData data];
[c start];
}
或
NSURLConnection* c = [[NSURLConnection alloc] initWithRequest:r delegate:self startImmediately:YES];
if (c) {
d = [NSMutableData data];
}