长轮询和applicationDidEnterBackground:

时间:2012-03-24 01:32:29

标签: iphone objective-c ios xcode long-polling

我正在编写一个非常简单的聊天应用程序,并且想知道当应用程序进入后台时如何暂停长轮询选择器。

目前,我有一个Chatroom类(A UIView)来处理长轮询,如下所示:

-(void)startPolling
{
    [self performSelectorInBackground:@selector(longPoll) withObject: nil];
}

- (void) longPoll {

    //Poll the Requested URL...

    NSData* responseData = [NSURLConnection sendSynchronousRequest:request
                                                 returningResponse:&response error:&error];

    [self performSelectorOnMainThread:@selector(dataReceived:) 
                           withObject:responseData waitUntilDone:YES];
    [self performSelectorInBackground:@selector(longPoll) withObject: nil];
}

-(void) dataReceived: (NSData*) data
{    
   //Reload my Tableview etc.. 
}

如何在应用程序返回前台之前使用applicationDidEnterBackground:暂停longPoll选择器?或者这是由应用程序代表自动完成的吗?

由于

1 个答案:

答案 0 :(得分:1)

请求将自动暂停。不能保证请求在恢复后必然成功,因此您必须处理错误,但不应该中断。

请注意,可能有更好的方法来编写它,而不是使用performSelectorInBackground:,它总是会旋转新的硬件线程。对于初学者来说,简单地在longPoll内循环而不是为新请求启动新线程可能更好。