如何在后台线程中每5秒运行一次任务,而不需要在ios中使用块UI



我正在开发聊天应用程序,在聊天屏幕上,我的应用程序需要每隔5秒检查一次新消息。我想在后台线程中这样做,这样我的应用程序就不会被UI阻止。我尝试了下面的代码,但当用户键入消息时,UI似乎被阻止了。此外,当用户退出聊天屏幕时,我无法启动此任务。

这是我尝试过的代码:

viewwillAppear() 调用getLatestMessagesWithInterval()

-(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()从服务器获取消息。服务器将在块中返回。执行完数据后,我在主线程中重新加载表视图。请。帮我纠正一下。提前谢谢。

与API异步通信,例如使用AFNetworking,您的UI不会被阻止,您还可以设置每秒的计时器并调用类似的东西

if (numberOfSeconds % 5 == 0) {
     numberOfSeconds = 0;
     retrieveLatestChatMessages()
}

两个选项

选项1

使用NSTimer每5秒调用一次该方法。

我建议不要使用它。

选项2

有一个基于TCP的聊天消息应用程序。

这将是聊天信息的最佳选择。


编辑1

学习如何根据您的语言使用TCP。对于iOS TCP,请遵循链接

http://www.tekritisoftware.com/sites/default/files/Socket_Programing_for_IOS.pdf

最新更新