【发布时间】:2014-09-07 11:09:46
【问题描述】:
我正在开发聊天应用程序,在聊天屏幕中,我的应用程序需要每 5 秒检查一次新消息。我想在后台线程中执行此操作,这样我的应用程序就不会被阻止 UI。我尝试了下面的代码,但是当用户输入消息时,UI 似乎被阻止了。此外,当用户退出聊天屏幕时,我无法触发此任务。
这是我尝试过的代码:
getLatestMessagesWithInterval() 在viewwillAppear() 中被调用
-(void) getLatestMessagesWithInterval
{
NSLog(@"GET MESSAGE INTERVAL");
[self retrieveLatestChatMessages];
// Call this method again using GCD
dispatch_queue_t q_background = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0);
double delayInSeconds = 5.0;
dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, delayInSeconds * NSEC_PER_SEC);
dispatch_after(popTime, q_background, ^(void){
[self getLatestMessagesWithInterval];
});
}
-(void) retrieveLatestChatMessages
{
if([[NSUserDefaults standardUserDefaults] boolForKey:@"LoggedIn"]) {
NSDictionary * userDictionary = [[NSUserDefaults standardUserDefaults] dictionaryForKey:@"SessionDictionary"];
.....
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
[[LSDataManager sharedDataManager] getLatestMessagesWithAuthKey:authenKey andLimit:limit withBlock:^ (NSDictionary* responseDict)
{
if (responseDict) {
[self loadDataFromServer:responseDict];
NSArray* lastMessageArray= nil;
//filter message data
if (self.MessagesArray.count >0) {
//perform data
self.TempdataSource = [[[ContentManager sharedManager] generateConversation:lastMessageArray withSenderID:self.senderID] mutableCopy];
//compare 2 arrays
if ([self.TempdataSource count] == [self.dataSource count]) {
NSLog(@"both are same");
}
else{
NSLog(@"both are different");
self.dataSource = [self.TempdataSource mutableCopy];
dispatch_async(dispatch_get_main_queue(), ^(){
//Add method, task you want perform on mainQueue
[self refreshMessages];
});
}
}
}
}
}];
});
}
}
我已致电retrieveLatestChatMessages() 从服务器获取消息。服务器将在块中返回。执行数据后,我在主线程中重新加载 tableview。请。帮我纠正它。提前致谢。
【问题讨论】:
标签: ios objective-c multithreading background nstimer