首先,我不认为这个问题已经存在,但我同意有类似的帖子,请继续阅读。
我的问题是:如何在他的“连接”状态中中止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
,这没关系。但我的问题是:在服务器发送响应之前如何中止我的连接,而不等待整个超时?
答案 0 :(得分:1)
您仍然可以呼叫[NSURLConnection cancel]
取消连接,并且不再进行委派呼叫。请记住,如果要重新连接,则必须创建新的连接对象。从你的问题中我推断出你在接收任何委托调用之前如何进行这个cancel
调用有问题,是这样吗?
另外,考虑将NSURLSession API用于数据任务,因为在大多数情况下这可能是处理网络的更好方法。
编辑(当您添加代码时):
首先,请注意,在运行循环中添加一个计时器并不会改变这里的任何内容,因为NSTimer不被视为运行循环的输入源(如果你真的"什么都不做" )。
第二 - 如果你将m_bRunLoop设置为false,你可以在某个地方进行,但是你没有提供代码 - 但这将取消你的连接,所以让我们为这个地方命名&#34 ; 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不是线程安全的,你不应该从不同的线程调用它的方法。