微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

在iOS中定期在后台线程中执行任务

我是iOS中的新手我正在研究应用程序需要运行一个任务,从后台线程中的服务器获取数据,因为我不想在主线程中锁定UI.这个任务需要很长时间,我尝试使用NSTimer,但它仍然锁定UI.我的任务是检查聊天屏幕中的新消息,我需要每5秒调用一次这个任务.如果我使用NSTimer,当输入文本时,文本似乎在此任务执行时冻结一会儿.有没有办法处理这个任务没有锁UI.请给我一些建议.非常感谢.

==更新代码==

- (void)performBackgroundTask
{
    dispatch_async(dispatch_get_global_queue(disPATCH_QUEUE_PRIORITY_DEFAULT,0),^{
        //Do background work

        if([[NSUserDefaults standardUserDefaults] boolForKey:@"LoggedIn"]) {
            NSDictionary * userDictionary = [[NSUserDefaults standardUserDefaults] dictionaryForKey:@"SessionDictionary"];

            Nsstring *authenKey= [userDictionary valueForKey:@"authToken"];

            Nsstring* limit = @"1000";

            [[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) {

                         if (!self.isSeller) {

                             lastMessageArray = [self filterMessageData:self.MessagesArray withProductID:self.productID withSellerID:self.receiverID withBuyerID:self.senderID];
                         }
                         else
                         {
                             lastMessageArray = [self filterMessageData:self.MessagesArray withProductID:self.productID withSellerID:self.senderID withBuyerID:self.receiverID];
                         }

                         NSLog(@"filter array %@",lastMessageArray);

                         if([lastMessageArray count] >0){
                             //[self loadMessages:lastMessageArray];
                             if (self.TempdataSource == nil) {
                                 self.TempdataSource = [NSMutableArray array];
                             }
                             else
                             {
                                 [self.TempdataSource removeAllObjects];
                             }

                             self.TempdataSource = [[[ContentManager sharedManager] generateConversation:lastMessageArray withSenderID:self.senderID] mutablecopy];

                         }
                     }
                 }
             }];
        }


        dispatch_async(dispatch_get_main_queue(),^{
            //Update UI

            //compare 2 arrays
            if ([self.TempdataSource count] == [self.dataSource count]) {
                NSLog(@"both are same");
            }
            else{
                NSLog(@"both are different");
                self.dataSource = [self.TempdataSource mutablecopy];

                [self refreshMessages];
            }

        });
    });
}

解决方法

使用NSTimer调度任务确实是正确的方法.您只需要确保在背景线程上运行沉重的非UI代码.这是一个例子
- (void)viewDidLoad {
    [super viewDidLoad];    
    [self startTimedTask];
}

- (void)startTimedTask
{
    NSTimer *fiveSecondTimer = [NSTimer scheduledTimerWithTimeInterval:5.0 target:self selector:@selector(performBackgroundTask) userInfo:nil repeats:YES];
}

- (void)performBackgroundTask
{
    dispatch_async(dispatch_get_global_queue(disPATCH_QUEUE_PRIORITY_DEFAULT,^{
        //Do background work
        dispatch_async(dispatch_get_main_queue(),^{
            //Update UI
        });
    });
}

原文地址:https://www.jb51.cc/iOS/336913.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐