web-dev-qa-db-fra.com

Exécution périodique d'une tâche dans le thread d'arrière-plan dans iOS

Je suis nouveau sur iOS. Je travaille sur l'application doit exécuter une tâche pour obtenir des données du serveur dans le thread d'arrière-plan car je ne veux pas verrouiller l'interface utilisateur dans le thread principal. Cette tâche prendra beaucoup de temps, j'ai essayé d'utiliser le NSTimer mais c'est toujours verrouiller l'interface utilisateur. Ma tâche consiste à vérifier les nouveaux messages dans l'écran de discussion, je dois appeler cette tâche toutes les 5 secondes. Si j'utilise NSTimer, lors de la saisie de texte, le texte semble se figer un moment pendant l'exécution de cette tâche. Existe-t-il un moyen de traiter cette tâche sans verrouiller l'interface utilisateur. Veuillez me donner quelques conseils. Merci beaucoup.

== METTRE À JOUR LE CODE ==

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

        });
    });
}
18
NTNT

La planification de la tâche à l'aide d'un NSTimer est en effet la bonne solution. Vous avez juste besoin de vous assurer que vous exécutez votre code non-interface utilisateur lourd sur un thread d'arrière-plan. Voici un exemple

- (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
        });
    });
}
34
Stavash
dispatch_async(dispatch_get_global_queue( DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^(void){
    //Background Thread
    dispatch_async(dispatch_get_main_queue(), ^(void){
        //Run UI Updates
    });
});

Essaye ça

15
Merlea Dan