NSTIMER seems to be ignored - ios

I have created a program and found an error that i cannot seem to work out.
I have stripped the problem out to recreate in a brand new project but it still re occurs.
The problem is when i press the BUTTON the image changes but at a much faster speed than the speed set up in NSTIMER but only the first time the button is pressed.
If i carry on pressing the button the image changes at the speed i require.
IT ONLY HAPPENS ON THE FIRST TIME ROUND AND I AM USING A TOUCH DOWN EVENT ( ALTHOUGH I HAVE TRIED TOUCH UP INSIDE )
This only happens the first time and is extremely important that the first time is the same timing as the rest.
I am aware of various discussions as to the accuracy of NSTIMER anyway , but i dont think it is relevant to my question
here is my .h
- (IBAction)slap:(id)sender {
NSString *imagechange4 = [NSString stringWithFormat:#"onehandedplayer2.png"];
//player2 is an UIButton IBOutlet
[player2 setImage:[UIImage imageNamed:imagechange4]];
[NSTimer scheduledTimerWithTimeInterval:0.5 target:self selector:#selector(handsback1) userInfo:nil repeats:NO];
}
-(void)handsback1 {
NSString *imagechange3= [NSString stringWithFormat:#"hands rotated.png"];
[player2 setImage:[UIImage imageNamed:imagechange3]];
}

Try using performSelector -
[self performSelector:#selector(handsback1) withObject:nil afterDelay:0.5];
It's really easy & reliable.

Just had an idle couple of minutes (!) & came across this again - it occurred to me that you could be mistaking the button highlighting when pressed as the image change - have you unchecked the button's "Highlighted Adjusts Image" property in IB's Attributes Inspector?
Unlikely perhaps, but you never know...

Related

Thread issue where updating a label make a UIImageview invisible

I have a situation that is confusing me lots. I have a class that has 2 completely separate things: An animated UIImage and a UILabel. They have different outlets, are not connected.
When the app runs, it does this:
dispatch_async(dispatch_get_main_queue(), ^{
[self.monsterMachine setHidden:NO]; //monsterMachine is UIImageView
[self.monsterMachine startAnimating];
});
but then when I do this:
[self.futText setText:#"blah"]; // is UILabel
it causes the monsterMachine UIImageView to not animate anymore. Things I have found:
Right after I setText:#blah" I can use NSLog to watch and see that self.monsterMachine.isAnimated suddenly goes from 1 to 0, ie from YES to NO.
If self.futText is ALREADY saying "blah", then I can run setText:#"blah" on it as many times as I want and nothing happens, it is ONLY when I change it to some value other than blah that UIImageView stops animating and disappears
If I don't use main_queue to show and animate monsterMachine, it won't display at ALL, so how do I diagnose or fix this?
That's weird it works for me perfect. Did you call [self.futText setText:#"blah"]; in main queue also?
Here is a small answer to why setting text #"blah" won't stops the animation:
Strings like #"blah" are stored in stacks which have the same reference as long as they have the same context. In this case [self.futText setText:#"blah"] will do nothing because the internal implementions are like:
void setText:(NSString*) text {
if ( _text == text ) then return;//if reference is the same then do nothing
_text = text;
some rendering..
}

AppleWatch circle progress (or radial arc progress) with images error

I'm developing an app for Apple Watch using WatchKit and I need to implement a circular progress while recording audio, similar to Apple demos.
I don't know if WatchKit includes something to do it by default so I have created my own images (13 for 12 seconds [209 KB in total]) that I change with a timer.
This is my source code:
Button action to start/stop recording
- (IBAction)recordAction {
NSLogPageSize();
NSLog(#"Recording...");
if (!isRecording) {
NSLog(#"Start!");
isRecording = YES;
_timerStop = [NSTimer scheduledTimerWithTimeInterval:12.0
target:self
selector:#selector(timerDone)
userInfo:nil
repeats:NO];
_timerProgress = [NSTimer scheduledTimerWithTimeInterval:1.0
target:self
selector:#selector(progressChange)
userInfo:nil
repeats:YES];
} else {
NSLog(#"Stop :(");
[self timerDone];
}
}
Action when timer is finished or if tap again on the button
-(void) timerDone{
NSLog(#"timerDone");
[_timerProgress invalidate];
_timerProgress = nil;
[recordButtonBackground setBackgroundImageNamed:[NSString stringWithFormat:#"ic_playing_elipse_12_%d", 12]];
counter = 0;
isRecording = NO;
}
Method to change progress
- (void)progressChange
{
counter++;
NSLog(#"%d", counter);
NSString *image = [NSString stringWithFormat:#"ic_playing_elipse_12_%d", counter];
[recordButtonBackground setBackgroundImageNamed:image];
NSLog(image);
}
This is a gif showing the bug. It starts to show but change the image randomly until it gets a pair of seconds. (Note: I have already checked that the first images have the right progress)
Update (other solution): using startAnimating
There is a new way to show a circle progress using startAnimatingWithImagesInRange:duration:repeatCount
You need to specify the images range and the duration for your animation. See an example below:
[self.myElement startAnimatingWithImagesInRange:NSMakeRange(0, 360) duration:myDuration repeatCount:1];
I believe this is a side-effect of the way WatchKit interprets image names.
Image names ending in numbers are used to represent frames in an animated image, so "ic_playing_elipse_12_10" is being interpreted as the first frame of the image named "ic_playing_eclipse_12_1" and your 10th image gets displayed when you want it to display your first one.
You should be able to just change your image names so the number isn't the last part of the image name and it will fix it.
I know that this question is answered but I would like to explain better the solution of startAnimating.
[myElement startAnimatingWithImagesInRange:NSMakeRange(imageIdBegin, imageIdEnd) duration:duration repeatCount:repetitions];
In order to use this, you need a suite of images named like you want but with sequential ids. For example: progress_0.png, progress_1.png, progress_2.png, .., progress_n.png
You can decide the begin index and the end index using that values in NSMakeRange(imageIdBegin, imageIdEnd) just indicating the number id (not the full image name)
Of course, you will need to indicate the duration of the animation in seconds, WatchKit will interpolate for you to animate your images between init index and end index.
And finally, you can indicate if you want to repeat this animation (for example for a loading action) or not. If you don't want to repeat, you have to indicate 1.
I hope this can help more people to perform circle progress or another animations inside their AppleWatch applications :)

How to show buffered data on UISlider using MpMoviePlayerController in iOS?

I am using MPMoviePlayerController to play audio and I want to show the buffered data on slider like this ...
I want to show the buffer data like red section in slider. I have tried to google it. But I didn't get any solution for it.
and How to make slider customize?
Thanks in advance...
Yes We can Show stream data using MPMoviePlayerController by its playableDuration. I am explaining all these steps involved me to make this custom_slider for my customize player...
(You Can direct read step 4 if you only interested in programming part)
These are the steps:
Step 1: (First Design part) i done it using standard Controls...
In Interface Builder place your UISlider immediately on top of your UIProgressView and make them the same size.
On a UISlider the background horizontal line is called the track, the trick is to make it invisible. We do this with a transparent PNG and the UISlider methods setMinimumTrackImage:forState: and setMaximumTrackImage:forState:.
In the viewDidLoad method of your view controller add:
[ProgressSlider setMinimumTrackImage:minImage forState:UIControlStateNormal];
[ProgressSlider setMaximumTrackImage:transparentImage forState:UIControlStateNormal];
[progressBar setTrackImage:maxImage];
[progressBar setProgressImage:streamImage];
where ProgressSlider refers to your UISlider and progressBar to your UIProgressView.
and you can make transparent image programmatically like this.
UIGraphicsBeginImageContextWithOptions((CGSize){512,5}, NO, 0.0f);
UIImage *transparentImage = UIGraphicsGetImageFromCurrentImageContext(); UIGraphicsEndImageContext();
you can change the size of it according to your progress view track image height width... I use {512,5} you can use {1,1} for default slider and progress view.
Reference taken form this answer https://stackoverflow.com/a/4570100/3933302
Step 2:
Now I tried to set the track and progress image of UIProgressView. But it was not showing the track and progress image. then i found this solution...to use this library available in github. https://gist.github.com/JohnEstropia/9482567
Now I changed occurrences of UIProgressView to JEProgressView, including those in NIBs and storyboards.
Basically, you'd need to force assigning the images directly to the UIProgressView's children UIImageViews.
The subclass is needed to override layoutSubviews, where you adjust the heights of the imageViews according to the image sizes.
Reference taken from this Answer https://stackoverflow.com/a/22322367/3933302
Step 3:
But now the question is from which will you make the image for slider and progressView. This is explained in this tutorial and You can download the psd also.
http://www.raywenderlich.com/32167/photoshop-tutorial-for-developers-creating-a-custom-uislider
Step 4:
Now come to programming part..
by using the playable duration it is possible to show stream data..(which was my biggest problem)
Using MPMovieLoadStatePlayable we can get when The buffer has enough data that playback can begin, but it may run out of data before playback finishes.
https://developer.apple.com/library/ios/documentation/MediaPlayer/Reference/MPMoviePlayerController_Class/index.html#//apple_ref/c/tdef/MPMovieLoadState
Now in your PlayAudio method...place this code..
-(void) playAudio:(NSURL *) url {
.............
streamTimer= [NSTimer scheduledTimerWithTimeInterval:0.1 target:self selector:#selector(loadStateChange) userInfo:nil repeats:YES];
..........
}
and here is the definition of loadStateChange
-(void)loadStateChange
{
if(self.moviePlayer.loadState == MPMovieLoadStatePlayable){
[self.moviePlayer play];
slideTimer = [NSTimer scheduledTimerWithTimeInterval:0.5
target:self
selector:#selector(updateProgressUI)
userInfo:nil
repeats:YES];
[streamTimer invalidate];
}
else if(self.downloadList)
//if you are playing local file then it will show track with full red color
progressBar.progress= appDel.moviePlayerController.moviePlayer.duration;
}
and here is the definition of updateProgressUI
- (void)updateProgressUI{
if(self.moviePlayer.duration == self.moviePlayer.playableDuration){
// all done
[slideTimer invalidate];
}
progressBar.progress = self.moviePlayer.playableDuration/self.moviePlayer.duration ;
}
I hope this fully customize slider will help you lot in making custom player...I explained all my work in steps.....Thanks ....
You cannot do this with MPMoviePlayerController.
However if you switch to AVPlayer then you can use AVPlayerItem.loadedTimeRanges. It contains all information you need for visualization in your custom control.
There are number of questions that have been asked on that topic, for example:
AVPlayer streaming progress
According the documentation of MPMoviePlayerController (available here) you can use the playableDuration property to retrieve the duration that has been loaded by the player.
You would then have to subclass UISlider to draw the red part of your control in the drawRect: method.
As for AVPlayer you would call loadedTimeRanges (documentation here) on the AVPlayerItem representing your content. That would give you an array of (as of iOS 8) a single CMTimeRange representing the part of your media that has been buffered. I would advise using [NSArray firstObject] when retrieving the time range to protect your code against a possibly empty array.

How to display images in array, pause between each image? [duplicate]

This question already has answers here:
Calling sleep(5); and updating text field not working
(4 answers)
Closed 8 years ago.
In my Application, I have a NSMutableArray with UIImage in it.
I would like to display the first UIImage in the array for three seconds, and then to
display the second image.
All of this should happen when I press a UIButton.
Below is my code:
[testImageView setImage:[arr objectAtIndex:0]] ;
sleep(3) ;
[testImageView setImage:[arr objectAtIndex:1]] ;
testImageView is a UIImageView object on my screen.
When I'm running this code, my button remain pressed for three seconds and only the second image is displayed.
What should I do?
Try using one of the most obscure methods of UIImageView.
UIImageView *myImageView = [[UIImageView alloc] initWithFrame:...];
myImageView.animationImages = images;
myImageView.animationDuration = 3.0 * images.count;
[self.view addSubview:myImageView];
Then, when you wanna start animating
[myImageView startAnimating];
I don't know what you plan on doing with this, but 3 seconds might be too much. If you're doing some sort of presentation-ish, then this method might not be very good, since there's no easy way of going back.
The reason that your button remains pressed is because you slept main thread for 3 seconds, this means that nothing is going to happen to your application (at least the user interface) until thread is back to active.
There are multiple ways to achieve what you wish, but you must put a timer on the background thread. I would suggest you put the code to set the second image in another method first and make array into a property.
- (void)setImage
{
[testImageView setImage:self.yourArray[1]];
}
Then you can use one of the following ways to execute the method:
Use a NSTimer:
[NSTimer scheduledTimerWithTimeInterval:3.0 target:self selector:#selector(setImage) userInfo:nil repeats:NO]
Use performSelector method of NSObject:
[self performSelector:#selector(setImage) withObject:nil afterDelay:3.0];
Use Grand Central Dispatch.
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 3.0), dispatch_get_main_queue(), ^{
[self setImage];
});
Any of the ways described above will work.
Read more information about concurrency on the links below:
http://jeffreysambells.com/2013/03/01/asynchronous-operations-in-ios-with-grand-central-dispatchNS
https://developer.apple.com/library/ios/documentation/general/conceptual/concurrencyprogrammingguide/Introduction/Introduction.html
how to call a method of multiple arguments with delay
How can I delay a method call for 1 second?

Stuck with UIActionSheetPicker , iOS

This is going to be a very targeted question , as its for people that have actually used the UIActionSheetPicker before.
I used it in my iphone applications and everything worked great , but now that i tried to implement it on my ipad i experienced some problems.
The main problem is that on ipad the picker appears as a "bubble" or "info window" if you prefer , which points at the spot where it was called , like a button a text field etc.
Below is an example of it :
You can see that the "info window" is pointing at the animals button.
In my application i have 4 different buttons. 2 are in the top side of the screen and 2 at the bottom.
Those who are at the bottom , call the picker very well and the picker appears on top of the buttons pointing down on them.
However , the ones on the top of the screen (almost like the one in the image) when they call the picker the picker appears much lower on the screen and doesnt point at them as it should ...
I mean i expected to appear just under the buttons pointing at them (like in the image), but they are almost in the center of the screen pointing nowhere..
Any ideas? Has someone experienced this before?
EDIT
In the beginning , i was calling the ActionSheetPicker inside the buttons action like this:
- (IBAction)selectTopic:(UIControl *)sender {
[ActionSheetStringPicker showPickerWithTitle:NSLocalizedString(#"CHOOSE_TOPIC", nil) rows:self.topics initialSelection:self.selectedIndex target:self successAction:#selector(topicWasSelected:element:) cancelAction:#selector(actionPickerCancelled:) origin:sender];
//when user picks a new topic we clean the titleField to make sure selected title of previous topic doesnt mix up with new topic
titleField.text = #"";
}
Now i am trying to call it like this:
- (IBAction)selectTopic:(UIControl *)sender {
ActionSheetStringPicker *thePicker = [[ActionSheetStringPicker alloc] initWithTitle:NSLocalizedString(#"CHOOSE_TOPIC", nil) rows:self.topics initialSelection:self.selectedIndex target:self successAction:#selector(topicWasSelected:element:) cancelAction:#selector(actionPickerCancelled:) origin:sender];
thePicker.presentFromRect = topicField.frame;
[thePicker showActionSheetPicker];
//when user picks a new topic we clean the titleField to make sure selected title of previous topic doesnt mix up with new topic
titleField.text = #"";
}
Where topicField is my TextField.
Sadly the result is the same. Even now that i am specifying where i want the arrow to point , the picker is called 300 pixels down.
The strange thing is though that even with another other button that is a bit lower than the previous the picker is again exactly 300 pixels down.
EDIT2
After noticing that the picker shows 300 pixels down , i decided to manually make it show 300pixels up , to point exactly on my button.
I used the following code :
- (IBAction)selectTopic:(UIControl *)sender {
//[ActionSheetStringPicker showPickerWithTitle:NSLocalizedString(#"CHOOSE_TOPIC", nil) rows:self.topics initialSelection:self.selectedIndex target:self successAction:#selector(topicWasSelected:element:) cancelAction:#selector(actionPickerCancelled:) origin:sender];
ActionSheetStringPicker *thePicker = [[ActionSheetStringPicker alloc] initWithTitle:NSLocalizedString(#"CHOOSE_TOPIC", nil) rows:self.topics initialSelection:self.selectedIndex target:self successAction:#selector(topicWasSelected:element:) cancelAction:#selector(actionPickerCancelled:) origin:sender];
CGRect pickerFrame = topicField.frame;
pickerFrame.size.height -= 300;
thePicker.presentFromRect = pickerFrame;
[thePicker showActionSheetPicker];
//when user picks a new topic we clean the titleField to make sure selected title of previous topic doesnt mix up with new topic
titleField.text = #"";
}
Amazingly the button once again appears in the same position 300pixels down. I start to believe that this one may not be the property to alter the position of the picker.
Any ideas ?
Setting the presentFromRect in your calling code won't make a difference since it will be reset based on the sender within the ActionSheetPicker code, instead you are going to need to modify the source code of the library.
The following (unmerged) commit on github should resolve the issue On iPad, set the popover to point properly at its container.
Basically within the AbstractActionSheetPicker.m file modify the - (void)presentPickerForView:(UIView *)aView method like the following
- (void)presentPickerForView:(UIView *)aView {
if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad) {
self.presentFromRect = CGRectMake(0, 0, self.containerView.frame.size.width, self.containerView.frame.size.height);
[self configureAndPresentPopoverForView:aView];
}
else {
self.presentFromRect = aView.frame;
[self configureAndPresentActionSheetForView:aView];
}
}
After a brief look at the code, I would say that you want to make sure that the presentFromRect on the ActionPicker object is in the coordinates of the container that you are passing in on the init. For instance if I had one big view that contained a button:
This is untested:
UIView* someBigView = ... // get the big view
UIButton* someButton = ... // get the button that the big view contains
ActionSheetDatePicker* thePicker = [[ActionSheetDatePicker alloc] initWithTitle:#"Some Title"
datePickerMode:UIDatePickerModeDate
selectedDate:[NSDate date]
target:self
action:#selector(someMethod:)
origin:someBigView];
//the arrow should be pointing at the button
thePicker.presentFromRect = someButton.frame;
[thePicker showActionSheetPicker];
In my opinion, this library has a pretty big flaw in the fact that it takes an origin parameter that can be a button item or a container. It requires that you look at the source to understand it, instead of being (somewhat) obvious from the interface.

Resources