I have a method that programmatically will take a screenshot [self makeScreenshot]. But sometimes, when a rotation happens for example, the result can be very ugly with black parts in it. So I’m trying to make a method with a completion that will wait for the view controllers animations to finish, so that the screenshots can be made safely and always look nice. The call would maybe look something like this:
[self methodWithCompletionWhenAnimationsIsDone:^(BOOL finished) {
// now it's safe to make the screenshot.
UIImage *myScreenshot = [self makeScreenshot];
}];
But I cant figure out how the code for such a method would look like. Any suggestions?
I’ve tried to place screenshot code the - (void)viewDidLayoutSubviews-method and it didn't work. And I don't want to use any rotation callback methods either, because the problem occurs at other occasions as well.
I don't know which method for animation you are using, but I will give you an example of the default UIView animation with completion:
[UIView animateWithDuration:1.0 animations:^{
/* Some animation here */
} completion:^(BOOL finished) {
UIImage *myScreenshot = [self makeScreenshot];
}];
Maybe you try to perform it in background thread
[self methodWithCompletionWhenAnimationsIsDone:^(BOOL finished) {
dispatch_async(dispatch_get_main_queue(), ^{
UIImage *myScreenshot = [self makeScreenshot];
});
}];
Related
I want to show loading animation while I am doing some initialisation. So I want to spin my (UIImageView*)_LogoImage until my initialisation will be completed. Then, after initialisation will be finished, I want to scale my _LogoImage. So, all this things begins from viewDidAppear, where I am calling beginLoading: method.
-(void)viewDidAppear:(BOOL)animated{
[super viewDidAppear:animated];
[self beginLoading];
}
Here, I am starting my spin animation. Assume, I am doing some initialisation in the next two code lines, I changed them to make a thread sleep to make a similar behaviour of my initialisation code. Then I am calling stopSpin: method to make the next half circle and to do my last scaling animation.
-(void)beginLoading{
[self startSpin];
[self sleepAction:3.0f];
[self sleepAction:1.0f];
[self stopSpin];
}
-(void)sleepAction:(float)sleepTime{
NSLog(#"SleepTime:[%f]",sleepTime);
[NSThread sleepForTimeInterval:sleepTime];
}
Here's my spinning code, which I am calling recursively until my BOOL refreshAnimating is Equal to YES. if not - running the last scaling animation
-(void)startSpin{
[UIView animateWithDuration:0.4
delay:0
options:UIViewAnimationOptionCurveLinear
animations:^{
_LogoImage.transform = CGAffineTransformMakeRotation(M_PI);
}
completion:^(BOOL finished){
[UIView animateWithDuration:0.4
delay:0
options:UIViewAnimationOptionCurveLinear
animations:^{
_LogoImage.transform = CGAffineTransformMakeRotation(0);
}
completion:^(BOOL finished){
if (refreshAnimating) {
[self startSpin];
}else{
[self refreshFinished];
}
}];
}];
}
-(void)stopSpin{
refreshAnimating = NO;
}
-(void)refreshFinished{
[UIView animateWithDuration:0.4 animations:^{
[_LogoImage setTransform:CGAffineTransformMakeScale(2, 2)];
}];
}
The problem is that my animation is not running, until the last initialisation code line completes. And after completion - I can see only the last animation. I was trying to put some code performing in the background and main thread, but I didn't run the way I want.
The rotation animation should start when the view appears, and continue until my initialisation code complete - then I want to see my last scale animation, which will indicate that my initialisation is completed.
Please, help.
All animations run on main thread and if you use sleep, it blocks your animations(main thread). Instead you can use a library like: MBProgressHUD please feel free to ask further questions.
Edit
-(void)startSpin{
_LogoImage.transform = CGAffineTransformMakeRotation(M_PI);
[UIView animateWithDuration:0.4
delay:0
options:UIViewAnimationOptionCurveLinear
animations:^{
_LogoImage.transform =CGAffineTransformMakeRotation(0);
}
completion:nil];
}
Can you try this. I think that is what are trying to do.
As #Ersin Sezgin said, all animations run on main thread.
So now, I am doing initialisation in background with completion block handler, which is forcing stopSpin: after initialisation completes.
Here's some code block. For better readability there's typedef of block.
typedef void(^OperationSuccessCompletionHandler)(BOOL success);
in .m file
-(void)sleepAction:(OperationSuccessCompletionHandler)success{
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
// We are doing initialisation here
BOOL isOperationSuccess = YES // Assume initialisation was successful
success(isOperationSuccess);
});
}
So now we can do this in another way
-(void)beginLoading{
[self startSpin];
[self sleepAction:^(BOOL success){
[self sleepAction:^(BOOL success){
[self stopSpin];
}];
}];
}
I have a method which can create and animate view
- (void) draw {
UILabel* label = [[UILabel alloc] initWithFrame:CGRectMake(57, 353, 350, 80)];
[self.view addSubview:label];
[UIView animateWithDuration:3
delay:0
options:UIViewAnimationOptionCurveLinear
animations:^{
[UIView animateWithDuration:2
delay:0
options:UIViewAnimationOptionCurveLinear
animations:^{
label.alpha = 0;
} completion:^(BOOL finished) {
[self.view willRemoveSubview:label];
}];
} completion:^(BOOL finished) {
}];
}
This method called when button was clicked. But if I click fast, the new views appear without waiting when the previous has finished. I want to create a queue of methods, like, when I tap on button, the new event is pushing to the queue, and all events are waiting when the previous one is finished, to start. Maybe I can do this with NSOperationQueue or GCD ?
As was already mentioned, what's up with the nested animateWithDuration:. Also and more to the point, You probably don't want to do anything with NSOperationQueue or GCD because all animations must be done on the main thread. If you did really want to do some threading you'd end up with something like
-(void)draw
{
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0), ^{
dispatch_sync(dispatch_get_main_queuem ^{
//do your animations and pray you don't cause deadlock
}
}
}
What you should probably do is disable the button when you press it, and re-enable it in the completion block of the animation
Why are you nesting the animateWithDuration:... call? I believe you can eliminate some of that complexity by only having a single call to animateWithDuration:...
To answer your actual question, you can use a simple queue made with a NSMutableArray. You can encapsulate your animation call as an object (either full custom or simply as a block or an NSInvocation) and push that object into the array. In the scenario you describe everything is running on the main thread, so you don't have to do any synchronization. Simply have a flag (isRunning) that you set when you start animating, and on completion try to see if there's another animation to start. Otherwise set the flag to false.
That should avoid any GCD calls.
Hi everyone,
small question.
I have an UIView class that I created, AnimatedUIView.
In the init, I create a subview that I animate like this:
- (void)animateView{
[UIView animateWithDuration:4.0
delay:1.0
options: nil
animations:^{
// Animation PART 1
}
completion:^(BOOL completed){
[UIView animateWithDuration:4.0
animations:^{
// Animation PART 2
}
completion:^(BOOL completed){
[self animateView];
}
];
}
];
}
I have to call [self animateView] myself in the second completion block rather than using option repeat because I want to delay 1 second only the first animation.
Everything works fine, I alloc and init my view and add it as a subview, and it is animated as should.
But, when I close my superview, I guess ARC does its work and deallocs the animatedView, but my CPU goes 100 % !
I have investigated and if I comment the call to [self animateView], my CPU doesn't skyrocket when I close the superview.
So I've managed to solve the problem (by putting a condition before the call and changing a boolean value before closing the superview, keepAnimating = NO) , I just wanted to understand WHY it does this?
Why does it try to keep animating, and why does it use so much CPU?
If I put an NSLog in the completion block, I first see it every 8 seconds, but when I close the superview, the NSLog just keeps appearing every ms...
BTW: it relates to this question : UIView animation using 90%CPU , which was not really answered. Thanks a lot!
CPU going to 100% almost always means infinite recursion.
We can only guess because only Apple knows what's inside the animation source code.
In this case I guess this could be caused by triggering the animation when the animation cannot run anymore (e.g. there is no layer since we are in dealloc state). That would mean the completion handler is called immediately and that leads to infinite recursion.
There are safer ways to create infinite animations (e.g. using CAAnimation on the layer).
You should not use self in side the block. It will create a retain cycle. If it is necessary to call self create a weak self pointer. Code like this
__weak typeof(self) weakself = self;
[UIView animateWithDuration:4.0
delay:1.0
options: nil
animations:^{
// Animation PART 1
}
completion:^(BOOL completed){
[UIView animateWithDuration:4.0
animations:^{
// Animation PART 2
}
completion:^(BOOL completed){
[weakself animateView];
}
];
}
];
But main issue with your code is you calling animateView recursively without any base case. So i consuming CPU cycles... do not use animateView without base case.
Try using timer
Write following line in your viewDidLoad or any where else from where you want animation to start.
[NSTimer scheduledTimerWithTimeInterval:9 target:self selector:#selector(animateView) userInfo:nil repeats:YES];
// 9 is total animation duration.....
update your animateView method as follows:
- (void)animateView{
[UIView animateWithDuration:4.0
delay:1.0
options: nil
animations:^{
// Animation PART 1
}
completion:^(BOOL completed){
[UIView animateWithDuration:4.0
animations:^{
// Animation PART 2
}
completion:^(BOOL completed){
}
];
}
];
}
I can call some selector by this code
[self performSelector:<#(SEL)#> onThread:<#(NSThread *)#> withObject:<#(id)#> waitUntilDone:<#(BOOL)#>]
and the Thread will wait until this selector is working (if I set waitUntilDone:YES). My question is - Can i wait until some code is done?
for example. I have some subview, which loads with animation. Animation duration is 2 sec. And if i make some actions on background view, while animating, i have an error. I'd like to wait until animation is over. And I can't to make a selector, and use
[self performSelector:<#(SEL)#> onThread:<#(NSThread *)#> withObject:<#(id)#> waitUntilDone:<#(BOOL)#>]
Any suggestions? )
You can try this way
-(void)waitUntilDone:(void(^)(void))waitBlock {
//use your statement or call method here
if(waitBlock){
waitBlock();
}
}
And you need to use it as
[self.tableView waitUntilDone:^{
//call the required method here
}];
UIView animation gives this to you in the form of the block style animation
[UIView animateWithDuration:0.25f
animations:^{
// animations
} completion:^(BOOL finished) {
// run code when the animation is finished
}];
Wait until animation gets finished & then do rest of the things :
For eg:
[UIView animateWithDuration:duration
animations:^
{
//DO ANIMATION ADJUSTMENTS HERE
}
completion:^(BOOL finished)
{
//ANIMATION DID FINISH -- DO YOUR STUFF
}];
I have a tabbed application and when I click on the second tab, an animation should be performed and then other operations should be executed.
I have implemented the animation with [imageView startAnimating]; and everything works well. The problem is that I don't know how to intercept the end of the animation process, in order to perform other operations.
I know that UIImageView has no delegate methods. I know that the imageView.isAnimating property is not useful. I know that using a NSTimer, the operation is executed at the end of timer, even if, for example, in my case the user has changed tab.
Any ideas on how to solve this issue? How to intercept the end of the animation?
I believe using an NSTimer is the only way to get the behavior you want. However, when the timer fires, I would include a check in whatever method gets called to make sure the tab you're talking about is still open; or you could invalidate the timer once the user changes tabs.
Try thse when you are loading your UIImageView:
[UIView transitionWithView: destinationView
duration:0.2f
options:UIViewAnimationOptionTransitionFlipFromLeft
animations:^ {
//Funky Animation
}
completion:^(BOOL finished) {
if(finished) {
//Funky Completion Code
}
}];
or
[UIView transitionFromView: startView
toView: destinationView
duration:0.2
options:UIViewAnimationOptionTransitionFlipFromLeft
animations:^ {
//Funky Animation
}
completion:^(BOOL finished) {
if(finished) {
//Funky Completion Code
}
}];
completion:NULL];