简体   繁体   中英

Programmatically linked UIView block-based animations hang at the first time fired on iOS

In my project, the program fire an animation when querying the database, when it receives the response data, it fires another animation automatically to display the data.

-(void)queryDatabase{
    //...querying database ...
    [UIView animateWithDuration:0.4
                          delay:0
                        options:UIViewAnimationOptionBeginFromCurrentState
                     animations:^{ 
                       //...first animation block...
                     }
                     completion:^(BOOL finished){
                       //...first completion block...
                     }];
}

-(void)receivedResponse:(NSData *)responseData{
    [UIView animateWithDuration:0.4
                          delay:0
                        options:UIViewAnimationOptionBeginFromCurrentState
                     animations:^{ 
                       //...second animation block...
                     }
                     completion:^(BOOL finished){
                       //...second completion block...
                     }];
}

My problem is, when the program is initiated and fire the second animation at the first time received response, the "second animation block" is exactly executed, but the "second completion block" is not executed and the screen does not change until about 20 or more seconds passed. After that, when this cycle is invoked again, the second animation will always work correctly. How to fix?

Firstly, all UI code should execute on the main thread. You will get unexpected results if you don't abide by this. I've experienced nothing happening at all when I want some UI code to run, and apps hanging whenever I've mistakenly run UI code on a background thread. There are plenty of discussions on why UI code has to run on the main thread.

If you know you're receivedResponse method is going to execute on a thread other than the main thread, you can easily bring it back to the main thread using Grand Central Dispatch (GCD). GCD is a lot nicer to use than the performSelectorOnMainThread methods...

-(void)receivedResponse:(NSData *)responseData{
    dispatch_async(dispatch_get_main_queue(), ^{
        // put your UI code in here
    });
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM