3

我正在使用 Apple 文档中的代码进行一些 HTTP 通信。我可以成功连接到 URL,但我无法从我的服务器接收数据。

// create the request
NSURLRequest *theRequest=[NSURLRequest requestWithURL:[NSURL URLWithString:@"http://..."]
                        cachePolicy:NSURLRequestUseProtocolCachePolicy
                        timeoutInterval:60.0];
// create the connection with the request
// and start loading the data
NSURLConnection *theConnection=[[NSURLConnection alloc] initWithRequest:theRequest delegate:self];
if (theConnection) {
    // Create the NSMutableData that will hold
    // the received data
    // receivedData is declared as a method instance elsewhere
    NSMutableData *receivedData=[[NSMutableData data] retain];
} else {
    // inform the user that the download could not be made
}

原因可能是:

  1. receivedData在 Action 本身中声明。注释说我应该在别处声明它。我应该在哪里申报?我应该将其声明为控制器的财产吗?

  2. 如何[[NSMutableData data] retain]找到 URL 之外的 URL if{}

4

1 回答 1

5

当你使用 NSURLConnection 的 initWithRequest:delegate: 方法时,数据(连同其他东西)在一系列方法调用中被发送到委托对象。这些方法都是可选的,所以如果你的委托对象没有实现它们,连接对象就会跳过它们。

方法有很多,这里就不一一列举了,但是在 NSURLConnection 文档中都有详细的描述。要获取接收到的数据,您需要在委托对象上实现 -connection:didReceiveData:。这个方法会被调用,可能不止一次,一个 NSData 对象代表新接收到的数据。然后,您可以将其附加到您现有的 NSMutableData 对象,或者用它做任何其他有意义的事情。当在委托对象上调用 -connectionDidFinishLoading: 时,您将知道您已收到所有数据。

要回答您的两个具体问题:

  1. 是的,您应该将其声明为控制器对象的属性。您还应该确保在调用 NSURLConnection 的 initWithRequest:delegate: 之前分配对象,因为一旦创建连接对象,连接就会开始异步加载数据。或者,您可以在委托上实现 -connection:didReceiveResponse:,检查 HTTP 状态,然后创建数据对象。

  2. 可变数据对象无法找到您设置的 URL、连接或其数据,但如果您按照我描述的步骤操作,则可以在数据进入时向其添加数据,并使用当连接完成时。

于 2009-02-27T04:48:21.367 回答