我有一个向服务器发出 GET 请求的函数。它工作正常但由于某种原因它被调用了两次。我在按下按钮时调用函数。
这是函数代码:
-(void) GETasync: (NSString *) path{
receivedData = [[NSMutableData alloc] init];
NSURLRequest *request=[NSURLRequest requestWithURL:
[NSURL URLWithString: path]
cachePolicy:NSURLRequestReloadIgnoringLocalCacheData
timeoutInterval:60.0];
NSHTTPURLResponse * response;
NSError * error;
NSData * data = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
NSLog(@"data received");
}
所以我在输出中看到:
2012-03-07 16:36:41.509 KW2[24136:bf03] data received
2012-03-07 16:36:41.694 KW2[24136:bf03] data received
我也有一个 POST 请求的函数,它也是同样的问题。
最佳答案
我假设您在委托(delegate)方法 connection:didReceiveData:
中打印出该日志。一个连接可以多次调用该方法——事实上,它通常至少被调用两次。
来自文档:
当接收到数据时,代理会定期发送 connection:didReceiveData: 消息。委托(delegate)实现负责存储新接收到的数据。
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
// Append the new data to receivedData.
// receivedData is an instance variable declared elsewhere.
[receivedData appendData:data];
}
编辑:我看到您在最近的编辑中添加了日志记录信息(或者我可能没有立即看到它 - 我真可耻)。
您是否可能通过通知处理程序调用该方法?如果是这样,您是否可能为该通知进行了双重注册 -> 因此您的处理程序被调用了两次。
关于iOS HTTP 请求被调用两次,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9600999/