tab sheet icon guidelines buttons bar ios objective-c multithreading background-process

sheet - Ejecutar una tarea en subproceso de fondo periódicamente en iOS



menu ios (2)

Soy nuevo en iOS. Estoy trabajando en la aplicación para ejecutar una tarea para obtener datos del servidor en el subproceso en segundo plano, ya que no quiero bloquear la interfaz de usuario en el subproceso principal. Esta tarea llevará mucho tiempo, intenté usar el NSTimer pero todavía está bloqueado la interfaz de usuario. Mi tarea es verificar los mensajes nuevos en la pantalla de chat, necesito llamar a esta tarea cada 5 s. Si uso NSTimer, cuando ingrese texto, el texto parece congelarse un momento mientras se realiza esta tarea. ¿Hay alguna manera de procesar esta tarea sin bloqueo de interfaz de usuario. Por favor, dame algunos consejos. Muchas gracias.

== CÓDIGO DE ACTUALIZACIÓN ==

- (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]; } }); }); }


Programar la tarea utilizando un NSTimer es, de hecho, el camino correcto a seguir. Solo debes asegurarte de que estás ejecutando tu pesado código de no UI en un hilo de fondo. Aquí un ejemplo

- (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, 0), ^{ //Do background work dispatch_async(dispatch_get_main_queue(), ^{ //Update UI }); }); }


dispatch_async(dispatch_get_global_queue( DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^(void){ //Background Thread dispatch_async(dispatch_get_main_queue(), ^(void){ //Run UI Updates }); });

Prueba esto