我正在构建一个简单的聊天室应用程序,其中有一个NSURLConnection sendSynchronousRequest:将请求发送到服务器进行长轮询。我想显示一个流,该流在后台运行时始终向我的用户更新聊天提要。
我的应用程序还允许用户更改其聊天室,因此我需要关闭一个NSURLConnection并为相应的供稿打开另一个。
我当前的实现如下:
//in ViewController.m
dispatch_queue_t concurrentQueue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
dispatch_async(concurrentQueue, ^{
while (longPollBOOL){
NSArray *MSG = [self.currentChatFeed longPoll]; //infinitely call longPoll method
dispatch_sync(dispatch_get_main_queue(), ^{
if (MSG.count != 0) //if the longPoll method returns a non-empty array, stick it into the message feed on the device.
{
for (id element in MSG)
{
[self.messages addObject:element];
[self finishReceivingMessage];
}
}
});
}
});
我正在尝试通过设置BOOL = NO来终止while循环,但是它不起作用。应用中的另一个View Controller正在发送BOOL = NO。我想保证在开始另一个聊天室的另一个无限循环之前,该循环已停止。
在开始另一个长轮询过程之前,我想杀死一个给定聊天室的漫长轮询过程。有任何想法吗?
我这样做正确吗?
如果要取消任务,最好使用NSOperation
s对其建模。您可以轻松地做到这一点而无需子类化:
NSBlockOperation *blockOperation = [[NSBlockOperation alloc] init];
__weak __typeof(blockOperation) weakBlockOperation = blockOperation;
[blockOperation addExecutionBlock:^{
while (!weakBlockOperation.isCancelled) {
NSArray *MSG = [self.currentChatFeed longPoll]; //infinitely call longPoll method
dispatch_sync(dispatch_get_main_queue(), ^{
if (MSG.count > 0) {
for (id element in MSG) {
[self.messages addObject:element];
[self finishReceivingMessage];
}
}
});
}
}];
[queue addOperation:blockOperation];
比起您只需要保留对操作的引用,您就可以随时取消它。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句