如何从iPhone上的URL接收数据?

Chi*_*ong 3 iphone connection communication http nsurlconnection

我正在使用Apple的Document中的代码进行一些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
}
Run Code Online (Sandbox Code Playgroud)

原因可能是:

  1. receivedData在行动中宣布.注释说我应该在其他地方声明它.我应该在哪里申报?我应该将其声明为控制人的财产吗?

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

Tom*_*ton 5

当您使用NSURLConnection的initWithRequest:delegate:方法时,数据(以及其他内容)将在一系列方法调用中发送到委托对象.这些方法都是可选的,因此如果您的委托对象没有实现它们,那么连接对象就会跳过它们.

有很多方法,所以我不会在这里列出所有方法,但是它们都在NSURLConnection文档中有详细描述.要获取接收的数据,您需要在委托对象上实现-connection:didReceiveData :. 使用表示新接收数据的NSData对象,可能会多次调用此方法.然后,您可以将其附加到现有的NSMutableData对象,或者执行其他任何有意义的操作.您将知道在委托对象上调用-connectionDidFinishLoading:时,您已收到所有数据.

回答你的两个具体问题:

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

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