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?
Related
I have a modal view in which a countdown starts when the user had performed some action. At the end of the countdown, the modal view would close. The following is the procedure I have written towards that goal but unfortunately, it is causing some thread problems. Is there any way to rewrite this in a way that does not have potential thread issues?
- (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];
}
}
Edit: the picture shows what XCode tells me about the problem
More edit:
My code has changed to reflect vadian's answer. Here is the update
- (void)startCountDown {
NSLog(#"starting count down");
counter = 3;
[NSTimer scheduledTimerWithTimeInterval:0.5 target:self selector:#selector(countDown:) userInfo:nil repeats:YES];
}
- (void)countDown:(NSTimer *)timer {
if (counter == 3) {
countDownFlag = [[UIImageView alloc] init];
countDownFlag.frame = CGRectMake(0, 370, countDownFlag.frame.size.width, countDownFlag.frame.size.height);
countDownFlag.center = CGPointMake(width / 2, countDownFlag.center.y);
dispatch_async(dispatch_get_main_queue(), ^{
[self.view addSubview:countDownFlag];
});
} else if (counter == 0) {
[timer invalidate];
[self dismissViewControllerAnimated:YES completion:nil];
return;
}
NSArray *imageNameArray = #[#"", #"One", #"Two", #"Three"];
UIImage *image = [UIImage imageNamed:imageNameArray[counter]];
dispatch_async(dispatch_get_main_queue(), ^{
[self.countDownFlag setImage:image];
});
counter--;
}
I new guess that the problem probably lies in the code that calls the countdown. Here is the code that does this.
- (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"];
}
//>>>>>>>>>>>>>>>>>>>> the problem is probably here
[self startCountDown];
}
Any code that runs after changing language code fails. The problem is probably there.
Edit: the thread problem is gone but the countdown isn't happening anymore.
After I have moved the code in changeLanguage into the methods that call it, the problem is mysteriously gone. (Repetitive but it works.)
- (void)changeLanguageToEnglish {
[theLock lock];
if (hasRun == YES) {
[theLock unlock];
return;
}
hasRun = YES;
[userdefaults setBool:false forKey:#"myanmar"];
[userdefaults synchronize];
[self updateCurrentLanguageText];
if ([self isMyanmar]) {
[self changeLanguageFlag:#"MyanmarFlagBig"];
} else {
[self changeLanguageFlag:#"UnitedKingdomFlagBig"];
}
[self startCountDown];
[theLock unlock];
}
- (void)changeLanguageToMyanmar {
[theLock lock];
if (hasRun == YES) {
[theLock unlock];
return;
}
hasRun = YES;
[userdefaults setBool:true forKey:#"myanmar"];
[userdefaults synchronize];
[self updateCurrentLanguageText];
if ([self isMyanmar]) {
[self changeLanguageFlag:#"MyanmarFlagBig"];
} else {
[self changeLanguageFlag:#"UnitedKingdomFlagBig"];
}
[self startCountDown];
[theLock unlock];
}
But the problem is that the countdown isn't happening anymore.
You could use an NSTimer to perform the countdown and a static variable for the counter.
The method startCountDown starts the timer.
The method countDown:(NSTimer *)timer is called every 0.5 seconds. The passed NSTimer argument is exactly the timer which has been started.
it performs the action according to its value and decrements the counter. If the counter is 0, the timer is invalidated and the controller dismissed.
static UInt8 counter = 0;
- (void)startCountDown {
countDownFlag = [[UIImageView alloc] init];
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];
counter = 3;
[NSTimer scheduledTimerWithTimeInterval:0.5 target:self selector:#selector(countDown:) userInfo:nil repeats:YES];
}
- (void)countDown:(NSTimer *)timer {
if (counter == 0) {
[timer invalidate];
[self dismissViewControllerAnimated:YES completion:nil];
return;
}
NSArray *imageNameArray = #[#"", #"One", #"Two", #"Three"];
UIImage *image = [UIImage imageNamed:imageNameArray[counter]];
dispatch_async(dispatch_get_main_queue(), ^{
[self.countDownFlag setImage:image];
});
counter--;
}
Place static int i = 3; outside your method countDown, the way you did it it declares new variable every time you call that method.
I have a small sample project i'm using to figure out how to implement this on my main project. This simple project has 2 VC's both with segues to each other.
On the initial VC is a button which leads to the TimerVC (both using the same class).
The TimerVC has a button and a label. When the button is pressed the label will increase by 1 every second.
If the timer is on and I segue back to the initial VC and then to the TimerVC the timer continues but the label stops updating.
How can I keep the label updating? The timer keeps going in the back-end but once the segue happens the label stops updating.
EDIT: Code provided below. The Timer is also more complex to represent a little of what I'm trying to do.
VC.H
NSTimer * timer;
NSTimer * updateTimer;
#property (weak, nonatomic) IBOutlet UIButton *idleOutler;
- (IBAction)idleAttack:(id)sender;
VC.M
int enemy001Hp = 100;
int deadEnemy = NO;
int noHealth = 0;
bool enemy001Active = NO;
- (void) enemy1 {
enemy001Active = YES;
self.enemyHpLabel.text = [NSString stringWithFormat:#"%i", enemy001Hp];
}
- (void) enemyDamageTimer {
if (enemy001Active == YES) {
enemy001Hp -= 50;
self.enemyHpLabel.text = [NSString stringWithFormat:#"%i",enemy001Hp];
}
}
- (void) updateLabelTimer {
if (enemy001Active == YES) {
self.enemyHpLabel.text = [NSString stringWithFormat:#"%i", enemy001Hp];
}
}
- (void) stopTimer {
[timer invalidate];
timer = nil;
self.enemyHpLabel.text = [NSString stringWithFormat:#"0"];
}
- (void)viewDidLoad {
[super viewDidLoad];
[self enemy1];
if (enemy001Active) {
self.enemyHpLabel.text = [NSString stringWithFormat:#"%i", enemy001Hp];
} else if (enemy002Active == YES) {
self.enemyHpLabel.text = [NSString stringWithFormat:#"%i", enemy002Hp];
}
}
- (IBAction)idleAttack:(id)sender {
idleOn = YES;
self.idleOutler.hidden = YES;
timer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:#selector(enemyDamageTimer) userInfo:nil repeats:YES];
updateTimer = [NSTimer scheduledTimerWithTimeInterval:0.5 target:self selector:#selector(updateLabelTimer) userInfo:nil repeats:YES];
if (enemy001Active == YES) {
if (enemy001Hp <= 0) {
[self enemy2];
enemy001Active = NO;
enemy002Active = YES;
}
} else if (enemy002Active == YES) {
if (enemy002Hp <= 0) {
self.enemyHpLabel.text = [NSString stringWithFormat:#"0"];
enemy002Hp = 0;
enemy002Active = NO;
[self stopTimer];
}
}
}
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
Hi iam really new to coding and to start of i am making a really simple game in Xcode. The game is done but i do have a little problem. rarely at times when in game over pig.image does not change and the previous animation keeps on going even after [pig stopAnimation]... heres the code from when you get game over to where the image should change.....
-(void)gameover1{
[jetpacksound stop];
[self hitsound];
[pig stopAnimating];
[movementtimer invalidate];
if (score > highscorenumber) {
highscorenumber = score;
[[NSUserDefaults standardUserDefaults] setInteger:highscorenumber forKey:#"highscoresaved"];
}
else{
highscore.text = [NSString stringWithFormat:#"Try Harder Next Time"];
}
movementtimer = [NSTimer scheduledTimerWithTimeInterval:.035 target:self selector:#selector(gameover1movement) userInfo:nil repeats:YES];
bam.hidden = NO;
flash.hidden = NO;
background1.hidden = YES;
background2.hidden = YES;
background3.hidden = YES;
pauseg.hidden = YES;
scorelabel.hidden = YES;
fork1.hidden = YES;
fork2.hidden = YES;
fork3.hidden = YES;
fork4.hidden = YES;
knife1.hidden = YES;
knife2.hidden = YES;
knife3.hidden = YES;
knife4.hidden = YES;
poisoncloud.hidden = YES;
cake.hidden = YES;
}
-(void)gameover1movement{
pig.center = CGPointMake(pig.center.x, pig.center.y - 30);
if (IS_IPAD)
{
//do stuff for iPad
if (pig.center.y < 400) {
[self gameover2];
}
}
else
{
if(IS_IPHONE_5)
{
//do stuff for 4 inch iPhone screen
if (pig.center.y < 200) {
[self gameover2];
}
}
else
{
//do stuff for 3.5 inch iPhone screen
}
}
}
-(void)gameover2{
[movementtimer invalidate];
movementtimer = [NSTimer scheduledTimerWithTimeInterval:.035 target:self selector:#selector(gameover2movement) userInfo:nil repeats:YES];
pig.image = [UIImage imageNamed:#"DeadPig.png"];
background1.hidden = NO;
background2.hidden = NO;
background3.hidden = NO;
bam.hidden = YES;
flash.hidden = YES;
if (IS_IPAD)
{
//do stuff for iPad
pig.frame = CGRectMake(pig.center.x - 115, pig.center.y - 165, 230.0f, 330.0f);
if (pig.center.x < 115) {
pig.center = CGPointMake(115, pig.center.y);
}
if (pig.center.x > 653) {
pig.center = CGPointMake(653, pig.center.y);
}
background3.center = CGPointMake(384, 512);
background2.center = CGPointMake(384, 1536);
background1.center = CGPointMake(384, 2560);
}
else
{
if(IS_IPHONE_5)
{
//do stuff for 4 inch iPhone screen
pig.frame = CGRectMake(pig.center.x - 50, pig.center.y - 75, 100.0f, 150.0f);
if (pig.center.x < 50) {
pig.center = CGPointMake(50, pig.center.y);
}
if (pig.center.x > 270) {
pig.center = CGPointMake(270, pig.center.y);
}
background3.center = CGPointMake(160, 284);
background2.center = CGPointMake(160, 852);
background1.center = CGPointMake(160, 1420);
}
else
{
//do stuff for 3.5 inch iPhone screen
}
}
}
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!