Why my timer disappear at every milliseconds and seconds? - ios

Hello I have a problem with my timer and I don't understand where is the problem my problem is at every milesecunds or seconds my timer disappear and appear i don't understand why :
- (void)viewDidLoad {
[super viewDidLoad];
self.BtnA.transform = CGAffineTransformMakeRotation( M_PI );
_timer = [NSTimer scheduledTimerWithTimeInterval:0.1 target:self selector:#selector(substractTime) userInfo:nil repeats:YES];
[self reset:nil];
}
- (IBAction)touchBtnA:(id)sender {
if (enabledA) {
[self.BtnA setEnabled:NO];
[self.BtnB setEnabled:YES];
enabledA = NO;
enabledB = YES;
[self.BtnA setAlpha:0.33];
[self.BtnB setAlpha:1.0];
} else {
[self.BtnA setEnabled:YES];
[self.BtnB setEnabled:NO];
enabledA = YES;
enabledB = NO;
[self.BtnB setAlpha:0.33];
[self.BtnA setAlpha:1.0];
}
}
- (IBAction)touchBtnB:(id)sender {
if (enabledB) {
[self.BtnB setEnabled:NO];
[self.BtnA setEnabled:YES];
enabledB = NO;
enabledA = YES;
[self.BtnB setAlpha:0.33];
[self.BtnA setAlpha:1.0];
} else {
[self.BtnB setEnabled:YES];
[self.BtnA setEnabled:NO];
enabledB = YES;
enabledA = NO;
[self.BtnA setAlpha:0.33];
[self.BtnB setAlpha:1.0];
}
}
- (void)substractTime {
if (enabledA) {
_remainingTimeA--;
if (_remainingTimeA == 0)
{
[self pause:nil];
[self.BtnA setEnabled:NO];
}
[self updateTime:A];
}
if (enabledB) {
_remainingTimeB--;
if (_remainingTimeB == 0)
{
[self pause:nil];
[self.BtnB setEnabled:NO];
}
[self updateTime:B];
}
}
- (void)updateTime: (TimerType)type {
NSInteger time = type == A ? _remainingTimeA : _remainingTimeB;
NSInteger minutes = time / 600;
NSInteger seconds = (time/10) % 60;
NSInteger milliseconds = time % 10;
if (type == A)
{
[self.BtnA setTitle:[NSString stringWithFormat:#"%02d:%02d:%01d",minutes, seconds, milliseconds] forState:UIControlStateNormal];
}
else
{
[self.BtnB setTitle:[NSString stringWithFormat:#"%02d:%02d:%01d",minutes, seconds, milliseconds] forState:UIControlStateNormal];
}
}
- (IBAction)pause:(id)sender {
enabledA = enabledB = NO;
}
- (IBAction)reset:(id)sender {
enabledA = enabledB = NO;
[self.BtnA setEnabled:YES];
[self.BtnB setEnabled:YES];
_remainingTimeA = _remainingTimeB = 6000;
[self updateTime:A];
[self updateTime:B];
[self.BtnA setAlpha:1.0];
[self.BtnB setAlpha:1.0];
}
Thanks all for feature help.

You should know that NSTimer doesn't grant you absolute accuracy of repeating interval (1.1 in your case) of invoking selector. In other words, you should count difference between current and previous selector calls, that will be exact interval

Related

how to display the congratulation view in iPhone using objective -c

I am developing a learning app for preschool kids. This is my code:
numbersStoreArray = [[NSMutableArray alloc]initWithObjects:#"1.png",#"2.png",#"3.png",#"4.png",#"5.png",#"6.png",#"7.png",#"8.png",#"9.png",#"10.png", nil];
commonFunctionObject = [[SpeechCommonFunctions alloc]init];
commonFunctionObject.isRecordComplete = NO;
counter = 0;
isMicPresent = YES;
_confirmationPopupView.hidden = true;
[NSTimer scheduledTimerWithTimeInterval:2.0 target:self selector:#selector(repeatActionFire) userInfo:nil repeats:NO];
}
-(void)repeatActionFire
{
if(counter >= numbersStoreArray.count)
{
NSLog(#"finished");
[_numbersShowImageView removeFromSuperview];
[_speakerOrMicImageView removeFromSuperview];
UIImageView *congratzView = [[UIImageView alloc]initWithFrame:self.view.frame];
congratzView.image = [UIImage imageNamed:#""];
[self.view addSubview:congratzView];
}
else
{
[commonFunctionObject textToSpeechAction:numbersStoreArray :counter :_numbersShowImageView :_speakerOrMicImageView :isMicPresent];
[NSTimer scheduledTimerWithTimeInterval:10.0 target:self selector:#selector(ActionToCkeckRecordCompletion) userInfo:nil repeats:YES];
}
}
-(void)ActionToCkeckRecordCompletion
{
if(commonFunctionObject.isRecordComplete)
{
_confirmationPopupView.hidden = false;
}
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
- (IBAction)playButtonAction:(id)sender
{
[commonFunctionObject recordPlayAction];
}
- (IBAction)nextButtonAction:(id)sender
{
counter+=1;
_confirmationPopupView.hidden = true;
commonFunctionObject.isRecordComplete = NO;
if(commonFunctionObject.player.playing){[commonFunctionObject.player stop];}
[self repeatActionFire];
}
- (IBAction)retryButtonAction:(id)sender
{
_confirmationPopupView.hidden = true;
commonFunctionObject.isRecordComplete = NO;
if(commonFunctionObject.player.playing){[commonFunctionObject.player stop];}
[self repeatActionFire];
}
After completion of this, this entry to the repeatActionFire and show finished. My question is: I need to display the congratulation view after the completion of the game and need to use two buttons.
Buttons for:
to reach the homepage
to retry the game.
How to do this?

Threading failure with countdown

Pressing a button in my iOS app calls the changeLanguage method.
- (void)changeLanguage:(BOOL) isMyanmar {
if (hasRun == YES) {
return;
}
hasRun = YES;
NSUserDefaults * userdefaults = [NSUserDefaults standardUserDefaults];
[userdefaults setBool:isMyanmar forKey:#"myanmar"];
[userdefaults synchronize];
[self updateCurrentLanguageText];
if ([self isMyanmar]) {
[self changeLanguageFlag:#"MyanmarFlagBig"];
} else {
[self changeLanguageFlag:#"UnitedKingdomFlagBig"];
}
[self countDown];
}
- (void)countDown {
static int i = 3;
if (i == 3) {
i--;
UIImage *three = [UIImage imageNamed:#"Three"];
countDownFlag = [[UIImageView alloc] initWithImage:three];
countDownFlag.frame = CGRectMake(0, 370, countDownFlag.frame.size.width, countDownFlag.frame.size.height);
countDownFlag.center = CGPointMake(width / 2, countDownFlag.center.y);
[self.view addSubview:countDownFlag];
[self performSelector:#selector(countDown) withObject:nil afterDelay:0.5];
} else if (i == 2) {
i--;
UIImage *two = [UIImage imageNamed:#"Two"];
[countDownFlag setImage:two];
[self performSelector:#selector(countDown) withObject:nil afterDelay:0.5];
} else if (i == 1) {
i--;
UIImage *one = [UIImage imageNamed:#"One"];
[countDownFlag setImage:one];
[self performSelector:#selector(countDown) withObject:nil afterDelay:0.5];
} else {
[self dismissViewControllerAnimated:YES completion:nil];
}
}
The method used to run fine but recently is having trouble with threading at [self countDown].
What could be causing the problem and how can I resolve this?
Edit:
How changeLanguage gets called
Two methods call this method:
- (void)changeLanguageToEnglish {
[self changeLanguage:false];
}
- (void)changeLanguageToMyanmar {
[self changeLanguage:true];
}
How the button calls the methods:
[languageButton addTarget:self action:#selector(changeLanguageToEnglish) forControlEvents:UIControlEventTouchUpInside];

Unable to hear sound in iOS

In my app I've having trouble to hear a sound. In particular this is my code:
#import <QuartzCore/QuartzCore.h>
#import <AudioToolbox/AudioToolbox.h>
#import "ViewController.h"
#import "RIOInterface.h"
#import "KeyHelper.h"
#import "Toast+UIView.h"
#interface ViewController () {
BOOL watermarkReceived;
float frequencyRecived;
CABasicAnimation *theAnimation;
BOOL water1, water2, water3, water4, noWater;
}
#property(nonatomic)NSTimer *timer, *timer2;
#property(nonatomic,strong)AVAudioPlayer *player;
#property(nonatomic,strong)NSURL *url;
#end
#implementation ViewController
#synthesize isListening;
#synthesize rioRef;
#synthesize currentFrequency;
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
//self.labelPosition.font=[UIFont fontWithName:#"DBLCDTempBlack" size:20.0];
NSError *error;
self.url = [NSURL fileURLWithPath:[[NSBundle mainBundle]pathForResource:#"sms_alert_circles" ofType:#"mp3"]];
self.player = [[AVAudioPlayer alloc] initWithContentsOfURL:self.url error:&error];
AVAudioSession *session = [AVAudioSession sharedInstance];
NSError *setCategoryError = nil;
[session setCategory:AVAudioSessionCategoryPlayback withOptions:AVAudioSessionCategoryOptionMixWithOthers error:&setCategoryError];
[self.imageLed setImage:[UIImage imageNamed:#"image_led_red.png"]];
self.rioRef = [RIOInterface sharedInstance];
[rioRef setSampleRate:44100];
[rioRef setFrequency:394];//294
[rioRef initializeAudioSession];
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
- (IBAction)startListenWatermark:(UIButton *)sender {
if ([sender isSelected]) {
[self stopListener];
[UIApplication sharedApplication].idleTimerDisabled = NO;
[sender setSelected:NO];
[self.imageListening.layer removeAllAnimations];
[self.imageLed setImage:[UIImage imageNamed:#"image_led_red.png"]];
//self.labelPosition.font=[UIFont fontWithName:#"DBLCDTempBlack" size:20.0];
self.labelPosition.text = #"Nessuna postazione";
} else {
water1 = water2 = water3 = water4 = NO;
[self startListener];
[UIApplication sharedApplication].idleTimerDisabled = YES;
[sender setSelected:YES];
[self.imageLed setImage:[UIImage imageNamed:#"image_led_red.png"]];
self.labelPosition.text = #"Nessuna postazione";
theAnimation = [CABasicAnimation animationWithKeyPath:#"opacity"];
theAnimation.duration = 0.4;
theAnimation.repeatDuration = 10000;
theAnimation.autoreverses = YES;
theAnimation.delegate = self;
theAnimation.fromValue = [NSNumber numberWithFloat:1.0];
theAnimation.toValue = [NSNumber numberWithFloat:0.1];
[self.imageListening.layer addAnimation:theAnimation forKey:#"animateOpacity"];
}
}
#pragma mark Listener methods
- (void)startListener {
[self.rioRef startListening:self];
}
- (void)stopListener {
[self.rioRef stopListening];
}
- (void)frequencyChangedWithValue:(float)newFrequency {
frequencyRecived = newFrequency;
watermarkReceived = YES;
if (frequencyRecived > 18000) {
if (frequencyRecived >= 18000 && frequencyRecived <= 18110 && !water1) {
[self.timer invalidate];
self.timer = nil;
[self performSelectorOnMainThread:#selector(setTextInLabel:) withObject:#"1" waitUntilDone:YES];
water2 = water3 = water4 = NO;
water1 = YES;
noWater = YES;
}
if (frequencyRecived >= 18115 && frequencyRecived <= 18250 && !water2) {
[self.timer invalidate];
self.timer = nil;
[self performSelectorOnMainThread:#selector(setTextInLabel:) withObject:#"2" waitUntilDone:YES];
water1 = water3 = water4 = NO;
water2 = YES;
noWater = YES;
}
if (frequencyRecived >= 18255 && frequencyRecived <= 18440 && !water3) {
[self.timer invalidate];
self.timer = nil;
[self performSelectorOnMainThread:#selector(setTextInLabel:) withObject:#"3" waitUntilDone:YES];
water1 = water2 = water4 = NO;
water3 = YES;
noWater = YES;
}
if (frequencyRecived >= 18445 && !water4) {
[self.timer invalidate];
self.timer = nil;
[self performSelectorOnMainThread:#selector(setTextInLabel:) withObject:#"4" waitUntilDone:YES];
water1 = water2 = water3 = NO;
water4 = YES;
noWater = YES;
}
} else {
if (noWater) {
[self performSelectorOnMainThread:#selector(noWatermark) withObject:nil waitUntilDone:YES];
noWater = NO;
}
}
}
- (void)noWatermark {
self.timer = [NSTimer scheduledTimerWithTimeInterval:5.0 target:self selector:#selector(noPosition:) userInfo:nil repeats:NO];
}
- (void)noPosition:(NSTimer*)aTimer {
[self performSelectorOnMainThread:#selector(setTextInLabel:) withObject:#"Nessuna postazione" waitUntilDone:YES];
[self performSelectorInBackground:#selector(redLed) withObject:nil];
self.timer2 = [NSTimer scheduledTimerWithTimeInterval:5.0 target:self selector:#selector(resetFlags) userInfo:nil repeats:NO];
}
- (void)resetFlags {
water1 = water2 = water3 = water4 = NO;
}
- (void)redLed {
[self.imageLed setImage:[UIImage imageNamed:#"image_led_red.png"]];
}
- (void)setTextInLabel:(NSString*)position {
[self.timer invalidate];
self.timer = nil;
if ([position isEqualToString:#"Nessuna postazione"]) {
self.labelPosition.text = position;
}
self.labelPosition.text = position;
if (![position isEqualToString:#"Nessuna postazione"]) {
[self.player setVolume:1.0];
[self.player prepareToPlay];
[self.player play];
NSString *textForToast = [NSString stringWithFormat:#"Postazione %#", position];
UIImage *image = [[UIImage alloc]init];
if ([position isEqualToString:#"1"]) {
image = [UIImage imageNamed:#"image_smart.png"];
}
if ([position isEqualToString:#"2"]) {
image = [UIImage imageNamed:#"image_500.png"];
}
if ([position isEqualToString:#"3"]) {
image = [UIImage imageNamed:#"image_mini.png"];
}
if ([position isEqualToString:#"4"]) {
image = [UIImage imageNamed:#"image_aygo.png"];
}
[self.view makeToast:textForToast duration:5.0 position:#"bottom" title:#"Watermark ricevuto" image:image];
[self.imageLed setImage:[UIImage imageNamed:#"image_led_green.png"]];
}
}
#end
In particular, this class should hear (with microphone) an audio signal in which there are some tone with a frequency >= 18000 Hz. So I will make this: when it recognize a tone of a frequency >= 18000 Hz it should play a sound.
When I try to run the app on the device I hear the sound with a very low volume by using iPhone speaker, but when I plug the headphone I hear the sound with an high volume. I tried to run the app by using simulator and when I use simulator it works nice. Why's that? Can you help me to fix this class?
PS: to detect the frequency of sounds I'm using pitch detector.
I solved it, I post here the code:
#import <QuartzCore/QuartzCore.h>
#import <AudioToolbox/AudioToolbox.h>
#import "ViewController.h"
#import "RIOInterface.h"
#import "KeyHelper.h"
#import "Toast+UIView.h"
#interface ViewController () {
BOOL watermarkReceived;
float frequencyRecived;
CABasicAnimation *theAnimation;
BOOL water1, water2, water3, water4, noWater;
}
#property(nonatomic)NSTimer *timer, *timer2;
//#property(strong)AVAudioPlayer *player;
#property(nonatomic,strong)NSURL *url;
#end
#implementation ViewController
#synthesize isListening;
#synthesize rioRef;
#synthesize currentFrequency;
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
// NSError *error;
//
// self.url = [NSURL fileURLWithPath:[[NSBundle mainBundle]pathForResource:#"sms_alert_circles" ofType:#"mp3"]];
// player = [[AVAudioPlayer alloc] initWithContentsOfURL:self.url error:&error];
//
// AVAudioSession *session = [AVAudioSession sharedInstance];
//
// NSError *setCategoryError = nil;
// [session setCategory:AVAudioSessionCategoryPlayback withOptions:AVAudioSessionCategoryOptionMixWithOthers error:&setCategoryError];
[self.imageLed setImage:[UIImage imageNamed:#"image_led_red.png"]];
self.rioRef = [RIOInterface sharedInstance];
[rioRef setSampleRate:44100];
[rioRef setFrequency:394];//294
[rioRef initializeAudioSession];
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
- (IBAction)startListenWatermark:(UIButton *)sender {
if ([sender isSelected]) {
[self stopListener];
[UIApplication sharedApplication].idleTimerDisabled = NO;
[sender setSelected:NO];
[self.imageListening.layer removeAllAnimations];
[self.imageLed setImage:[UIImage imageNamed:#"image_led_red.png"]];
//self.labelPosition.font=[UIFont fontWithName:#"DBLCDTempBlack" size:20.0];
self.labelPosition.text = #"Nessuna postazione";
} else {
water1 = water2 = water3 = water4 = NO;
[self startListener];
[UIApplication sharedApplication].idleTimerDisabled = YES;
[sender setSelected:YES];
[self.imageLed setImage:[UIImage imageNamed:#"image_led_red.png"]];
self.labelPosition.text = #"Nessuna postazione";
theAnimation = [CABasicAnimation animationWithKeyPath:#"opacity"];
theAnimation.duration = 0.4;
theAnimation.repeatDuration = 10000;
theAnimation.autoreverses = YES;
theAnimation.delegate = self;
theAnimation.fromValue = [NSNumber numberWithFloat:1.0];
theAnimation.toValue = [NSNumber numberWithFloat:0.1];
[self.imageListening.layer addAnimation:theAnimation forKey:#"animateOpacity"];
}
}
#pragma mark Listener methods
- (void)startListener {
[self.rioRef startListening:self];
}
- (void)stopListener {
[self.rioRef stopListening];
}
- (void)frequencyChangedWithValue:(float)newFrequency {
frequencyRecived = newFrequency;
watermarkReceived = YES;
if (frequencyRecived > 18000) {
if (frequencyRecived >= 18000 && frequencyRecived <= 18110 && !water1) {
[self.timer invalidate];
self.timer = nil;
[self performSelectorOnMainThread:#selector(setTextInLabel:) withObject:#"1" waitUntilDone:YES];
water2 = water3 = water4 = NO;
water1 = YES;
noWater = YES;
}
if (frequencyRecived >= 18115 && frequencyRecived <= 18250 && !water2) {
[self.timer invalidate];
self.timer = nil;
[self performSelectorOnMainThread:#selector(setTextInLabel:) withObject:#"2" waitUntilDone:YES];
water1 = water3 = water4 = NO;
water2 = YES;
noWater = YES;
}
if (frequencyRecived >= 18255 && frequencyRecived <= 18440 && !water3) {
[self.timer invalidate];
self.timer = nil;
[self performSelectorOnMainThread:#selector(setTextInLabel:) withObject:#"3" waitUntilDone:YES];
water1 = water2 = water4 = NO;
water3 = YES;
noWater = YES;
}
if (frequencyRecived >= 18445 && !water4) {
[self.timer invalidate];
self.timer = nil;
[self performSelectorOnMainThread:#selector(setTextInLabel:) withObject:#"4" waitUntilDone:YES];
water1 = water2 = water3 = NO;
water4 = YES;
noWater = YES;
}
} else {
if (noWater) {
[self performSelectorOnMainThread:#selector(noWatermark) withObject:nil waitUntilDone:YES];
noWater = NO;
}
}
}
- (void)noWatermark {
self.timer = [NSTimer scheduledTimerWithTimeInterval:5.0 target:self selector:#selector(noPosition:) userInfo:nil repeats:NO];
}
- (void)noPosition:(NSTimer*)aTimer {
[self performSelectorOnMainThread:#selector(setTextInLabel:) withObject:#"Nessuna postazione" waitUntilDone:YES];
[self performSelectorInBackground:#selector(redLed) withObject:nil];
self.timer2 = [NSTimer scheduledTimerWithTimeInterval:5.0 target:self selector:#selector(resetFlags) userInfo:nil repeats:NO];
}
- (void)resetFlags {
water1 = water2 = water3 = water4 = NO;
}
- (void)redLed {
[self.imageLed setImage:[UIImage imageNamed:#"image_led_red.png"]];
}
- (void)setTextInLabel:(NSString*)position {
[self.timer invalidate];
self.timer = nil;
NSError *error;
self.url = [NSURL fileURLWithPath:[[NSBundle mainBundle]pathForResource:#"sms_alert_circles" ofType:#"mp3"]];
player = [[AVAudioPlayer alloc] initWithContentsOfURL:self.url error:&error];
AVAudioSession *session = [AVAudioSession sharedInstance];
NSError *setCategoryError = nil;
[session setCategory:AVAudioSessionCategoryPlayback withOptions:AVAudioSessionCategoryOptionMixWithOthers error:&setCategoryError];
if ([position isEqualToString:#"Nessuna postazione"]) {
self.labelPosition.text = position;
}
self.labelPosition.text = position;
if (![position isEqualToString:#"Nessuna postazione"]) {
[player setVolume:1.0];
[player prepareToPlay];
[player play];
NSString *textForToast = [NSString stringWithFormat:#"Postazione %#", position];
UIImage *image = [[UIImage alloc]init];
if ([position isEqualToString:#"1"]) {
image = [UIImage imageNamed:#"image_smart.png"];
}
if ([position isEqualToString:#"2"]) {
image = [UIImage imageNamed:#"image_500.png"];
}
if ([position isEqualToString:#"3"]) {
image = [UIImage imageNamed:#"image_mini.png"];
}
if ([position isEqualToString:#"4"]) {
image = [UIImage imageNamed:#"image_aygo.png"];
}
[self.view makeToast:textForToast duration:5.0 position:#"bottom" title:#"Watermark ricevuto" image:image];
[self.imageLed setImage:[UIImage imageNamed:#"image_led_green.png"]];
}
}
#end
I just put the initializer of the AVAudioPlayer into method setTextInLabel and it works.
Thank you!

Quiz app -next to display after Image result hides

I am new to App Development, sorry if I am asking silly questions :(
I am developing a Quiz App. Whenever I give a right or wrong answer, an image appears with right or wrong answer result, however it stays for a few seconds, but after that - it does not continue with the next question. It just shows my background images with buttons. How can I set a code, that it goes straight to a new question, when the result image is gone.
I will be very thankful for your help.
I just want that after the Result-image closes, the quiz continues with the next question.
This is the code i have setup in Game.m file.
-(void)RightAnswer{
ScoreNumber = ScoreNumber + 1;
Score.text = [NSString stringWithFormat:#"%i", ScoreNumber];
Answer1.hidden = YES;
Answer2.hidden = YES;
Answer3.hidden = YES;
CategorySelected.hidden = NO;
Next.hidden = NO;
imageQuestion.hidden = YES;
Results.hidden = NO;
Results.image = [UIImage imageNamed:#"right.png"]; [self performSelector:#selector(Results) withObject:nil afterDelay:2.0];
GameInProgress = YES;
}
-(void)WrongAnswer{
LivesNumber = LivesNumber - 1;
Lives.text = [NSString stringWithFormat:#"%i", LivesNumber];
Answer1.hidden = YES;
Answer2.hidden = YES;
Answer3.hidden = YES;
imageQuestion.hidden = YES;
CategorySelected.hidden = NO;
Next.hidden = NO;
Results.hidden = NO;
Results.image = [UIImage imageNamed:#"wrong.png"];[self performSelector:#selector(Results) withObject:nil afterDelay:2.0];
GameInProgress = YES;
if(LivesNumber ==0) {
Results.image = [UIImage imageNamed:#"gameover.png"];
GameInProgress = NO;
Exit.hidden = NO;
}
-(void)RightAnswer{
ScoreNumber = ScoreNumber + 1;
Score.text = [NSString stringWithFormat:#"%i", ScoreNumber];
Answer1.hidden = YES;
Answer2.hidden = YES;
Answer3.hidden = YES;
Answer1Correct ==YES;
CategorySelected.hidden = NO;
Next.hidden = NO;
imageQuestion.hidden = YES;
Results.hidden = NO;
Results.image = [UIImage imageNamed:#"right.png"]; [self performSelector:#selector(Results) withObject:nil afterDelay:2.0];
GameInProgress = YES;
}
I think the issue is that you never set Answer1Correct to anything. so if you add Answer1Correct ==YES to the correct answer method and Answer1Correct ==NO to the wrong method then it should work
-(void)Results{ // just change formate of answer.
Results.hidden = YES;
}
-(IBAction)Answer1: (id) sender{
if (Answer1Correct ==YES) {
[self RightAnswer];
}else{
[self WrongAnswer];
}
}
-(IBAction)Answer2: (id) sender{
if (Answer2Correct ==YES) {
[self RightAnswer];
}
else{
[self WrongAnswer];
}
}
-(IBAction)Answer3: (id) sender{
if (Answer3Correct ==YES) {
[self RightAnswer];
}
else{
[self WrongAnswer];
}
}
i may be wrong here but I think you need an if to the else.
But I could be wrong.
if(LivesNumber ==0) {
Results.image = [UIImage imageNamed:#"gameover.png"];
GameInProgress = NO;
Exit.hidden = NO;
}else{
donextcard();
}
if you want to know how to make that function we would need to see more of the code.

Tap gesture causes strange behavior

I’m building a reaction test that requires the user to tap on the target dot, while other non-target dots come down. It works most of the time but sometimes after tapping on a target dot it will display several other dots with weird behavior. I’ve been looking at the code for days and I can’t find the problem. Does anyone have any suggestions?
Thanks much. Here’s the code.
- (void)viewDidAppear:(BOOL)animated
{
[super viewDidAppear:animated];
// single tap gesture recognizer
self.myTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:#selector(theTap:)];
self.myTap.numberOfTapsRequired = 1;
[self.firstView addGestureRecognizer:self.myTap];
self.myTap.enabled = NO;
self.colorToHit = self.colorFromPreviousController;
[self KickOff];
}
- (void)viewDidLoad
{
[super viewDidLoad];
self.holdTheReactionTimes = [[NSMutableArray alloc] initWithCapacity:50];
self.firstTime = YES;
numberOfTries = 0;
}
#pragma mark - Utility Methods
- (void)setRandomLocationForView:(UIView *)view
{
CGRect sinkBounds = CGRectInset(self.firstView.bounds, view.frame.size.width/2, view.frame.size.height/2);
CGFloat x = arc4random() % (int)sinkBounds.size.width + view.frame.size.width/2;
CGFloat y = arc4random() % (int)sinkBounds.size.height + view.frame.size.height/2;
view.center = CGPointMake(x, y);
}
- (void)addLabel
{
[self stopDraining];
static NSArray *buttons = nil;
buttons = [[NSArray alloc] initWithObjects:
#"XX.png",
#"YY.png",
#"ZZ.png",
nil];
int theIndex = arc4random()%[buttons count];
NSLog(#"the index: %d", theIndex);
NSString *theImageName = [buttons objectAtIndex:theIndex];
CGRect anotherFrame = CGRectMake(10, 10, 64, 64);
UIView *anotherView = [[UIView alloc] initWithFrame:anotherFrame]
UIImageView *imageView1 = [[UIImageView alloc] initWithFrame:CGRectMake(-2, -2, 64, 64)];
imageView1.image = [UIImage imageNamed:theImageName];
[anotherView addSubview:imageView1];
[self setRandomLocationForView:anotherView];
[self.firstView addSubview:anotherView];
NSDate *date = [NSDate date];
timeOne = [date timeIntervalSince1970];
if (theIndex == self.colorToHit) {
NSLog(#"the right color");
self.isThisTheRightColor = YES;
self.myTap.enabled = YES;
numberOfTries += 1;
} else {
NSLog(#"the wrong color");
self.isThisTheRightColor = NO;
self.myTap.enabled = NO;
[self startDraining];
}
}
#pragma mark - View Animation
#define ANIMATE_DURATION 6.0
#define SLEEP_INTERVAL 0.5
- (void)theTap:(UITapGestureRecognizer *)gesture
{
NSLog(#"Tapped");
float tapInterval = 0;
CGPoint tapLocation = [gesture locationInView:self.firstView];
for (UIView *view in self.firstView.subviews) {
if (CGRectContainsPoint(view.frame, tapLocation)) {
NSLog(#"we hit one");
AudioServicesPlayAlertSound(kSystemSoundID_Vibrate); // added this 4-27
if (self.firstTime) {
NSDate *date = [NSDate date];
timeTwo = [date timeIntervalSince1970];
NSLog(#"TAP First time: %f", timeTwo);
self.firstTime = NO;
} else {
NSDate *date = [NSDate date];
timeTwo = [date timeIntervalSince1970];
NSLog(#"Second time: %f", timeTwo);
}
tapInterval = (timeTwo - timeOne);
NSLog(#"Time Interval: %f", tapInterval);
[view removeFromSuperview];
[self writeTimeStampToArray:tapInterval];
}
}
}
- (void)KickOff
{
for (UIView *view in self.firstView.subviews) {
[view removeFromSuperview];
}
if (self.firstView.window) {
[self addLabel];
}
}
- (void)writeTimeStampToArray:(float)timeStamp
{
NSNumber *timeObject = [NSNumber numberWithFloat: timeStamp];
[self.holdTheReactionTimes addObject:timeObject];
if (numberOfTries < NUMBER_OF_TRIES) {
[self addLabel];
} else {
[self nextScreen];
}
}
- (void)nextScreen
{
[self performSegueWithIdentifier: #"viewsummary" sender: self];
}
}
}
#pragma mark - Flipside View
- (void)ReactionViewControllerDidFinish:(int)trynumber
{
self.tryNumberInt = trynumber;
[self dismissViewControllerAnimated:YES completion:nil];
}
#define COUNTER 4
//////////////
// drain logic
- (void)drain:(NSTimer *)timer
{
[self drain];
}
#define DRAIN_DURATION 2.0
- (void)startDraining
{
self.drainTimer = [NSTimer scheduledTimerWithTimeInterval:DRAIN_DURATION/3
target:self
selector:#selector(drain:)
userInfo:nil
repeats:YES];
}
- (void)stopDraining
{
[self.drainTimer invalidate];
}
- (void)drain
{
for (UIView *view in self.firstView.subviews) {
CGAffineTransform transform = view.transform;
if (CGAffineTransformIsIdentity(transform)) {
UIViewAnimationOptions options = UIViewAnimationOptionCurveLinear;
[UIView animateWithDuration:DRAIN_DURATION/3 delay:0 options:options animations:^{
view.transform = CGAffineTransformRotate(CGAffineTransformScale(transform, 0.7, 0.7), 2*M_PI/3);
} completion:^(BOOL finished) {
if (finished) {
[UIView animateWithDuration:DRAIN_DURATION/3 delay:0 options:options animations:^{
view.transform = CGAffineTransformRotate(CGAffineTransformScale(transform, 0.4, 0.4), -2*M_PI/3);
} completion:^(BOOL finished) {
if (finished) {
[UIView animateWithDuration:DRAIN_DURATION/3 delay:0 options:options animations:^{
view.transform = CGAffineTransformScale(transform, 0.1, 0.1);
} completion:^(BOOL finished) {
if (finished) [view removeFromSuperview];
}];
}
}];
}
}];
}
}
[self addLabel];
}

Resources