2

我已经完全按照官方文档的指示进行了操作。我创建了一个控制台项目用于测试目的。然后我创建了一个名为 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

这无疑将在主线程和默认运行循环中执行。然而,没有调用委托方法。

我已经做了很多测试并阅读了很多帖子,但我仍然没有任何线索。

请帮我。这让我发疯。谢谢!

4

1 回答 1

0

I believe you're missing the part where you start the connection. The connection class offers another method for this, or you could just call it off of your "c" object.

NSURLConnection* c = [[NSURLConnection alloc] initWithRequest:r delegate:self];
if (c) {
    d = [NSMutableData data];
    [c start];
}

or

NSURLConnection* c = [[NSURLConnection alloc] initWithRequest:r delegate:self startImmediately:YES];
if (c) {
    d = [NSMutableData data];
}
于 2013-04-02T21:59:44.733 回答