首先,我认为这个问题已经不存在,但是我同意有类似的帖子,请继续阅读。
我的问题是:如何在“正在连接”状态下中止NSUrlConnection?我的意思是,建立连接后,我们可以使用NSUrlConnection cancel
方法取消请求。但是,在服务器未提供响应(在收到任何委托调用之前)达到超时之前,如何在“连接”状态中终止它?
谢谢你的时间!
编辑
我应该使用NSURLSessionTask
而不是NSUrlConnection
来做到这一点(及其方法cancel
)吗?
编辑2-代码示例
NSURLConnection* m_connection;
m_connection = [[NSURLConnection alloc] initWithRequest:request delegate:self startImmediately:NO];
if(m_connection){
[m_connection start];
m_timer = [NSTimer scheduledTimerWithTimeInterval: FLT_MAX
target: self selector: @selector(doNothing:)
userInfo: nil repeats:YES];
m_runLoop = [NSRunLoop currentRunLoop];
[m_runLoop addTimer:m_timer forMode:NSDefaultRunLoopMode];
while (m_bRunLoop && [m_runLoop runMode:NSDefaultRunLoopMode beforeDate:[NSDate distantFuture]]);
[m_connection cancel];
}
我使用连接来流数据。如您所见,目前我中止了将连接设置
m_bRunLoop
设置为false
的操作,并且可以。但是我的问题是:如何在服务器发送响应之前中止我的连接,而不等待整个超时? 最佳答案
您仍然可以呼叫[NSURLConnection cancel]
取消连接,并且没有其他委托呼叫。请记住,如果要重新连接,则必须创建一个新的连接对象。从您的问题中,我推断出您在接收任何委托调用之前如何进行此cancel
调用时遇到问题,是这样吗?
另外,考虑将NSURLSession API与数据任务一起使用,因为在大多数情况下,这可能是处理联网的更好方法。
编辑(添加代码时):
首先,请注意,在运行循环中添加计时器不会改变此处的内容,因为NSTimer不会被视为运行循环的输入源(如果您确实“什么也不做”)。
其次-如果将m_bRunLoop设置为false,则尽管未提供代码,但仍可以在某处进行操作-但这是取消连接的地方,所以我们将其命名为“ cancelConnection”方法。
修改您的代码,如下所示:
m_connection = [[NSURLConnection alloc] initWithRequest:request delegate:self startImmediately:NO];
if(m_connection){
yourConnectionThread = [NSThread currentThread]; // store your thread in instance variable
[m_connection start];
m_timer = [NSTimer scheduledTimerWithTimeInterval: FLT_MAX
target: self selector: @selector(doNothing:)
userInfo: nil repeats:YES];
m_runLoop = [NSRunLoop currentRunLoop];
[m_runLoop addTimer:m_timer forMode:NSDefaultRunLoopMode];
}
并在取消连接的地方实现方法,请记住,需要在开始连接的线程上调用cancel:
- (void)cancelConnection {
//m_bRunLoop = false <- this was before here
[m_connection performSelector:@selector(cancel) onThread:yourConnectionThread withObject:nil waitUntilDone:YES];
}
最后,作为评论,请记住-NSRunLoop不是线程安全的,您不应从不同的线程调用它的方法。
关于ios - 在“连接”状态期间中止NSUrlConnection,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/43088232/