我所做的正是this official documentation指示。我创建了一个控制台项目用于测试目的。然后我创建了一个名为 RequestSender 的类(参见下面的代码),并在主函数中创建了这个类的一个实例。
请求发送者.h:
#import <Foundation/Foundation.h>
@interface RequestSender : NSObject <NSURLConnectionDelegate> {
NSMutableData* d;
}
@end
请求发送者.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
这无疑将在主线程和默认运行循环中执行。然而,没有调用委托(delegate)方法。
我已经做了很多测试并阅读了很多帖子,但我仍然没有任何线索。
请帮我。这让我发疯。
谢谢!
最佳答案
我相信您缺少开始连接的部分。连接类为此提供了另一种方法,或者您可以从“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];
}
关于xcode - 为什么我的 NSURLConnection 委托(delegate)方法没有被调用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11337689/