Below is some code I’m working with.
What I want/expect:
- Image fades in; sound plays; delay; image fades out.
What happens
- Delay, sound plays, image fades in and then fades out immediately after
Any help much appreciated.
ViewController.m
[self fadein];
NSString *tempFN;
SystemSoundID soundID;
tempFN = [[NSString alloc] initWithFormat:@"%@.caf",
[myGlobals.gTitleArray objectAtIndex:myGlobals.gQuoteCountForLoop]];
NSString *soundFilePath = [NSString stringWithFormat:@"%@/%@", [[NSBundle mainBundle] resourcePath], tempFN];
NSURL *soundFileURL = [NSURL fileURLWithPath:soundFilePath];
UInt32 sessionCategory = kAudioSessionCategory_MediaPlayback;
AudioSessionSetProperty (kAudioSessionProperty_AudioCategory,
sizeof (sessionCategory),
&sessionCategory);
AudioServicesCreateSystemSoundID((__bridge CFURLRef)soundFileURL, &soundID);
AudioServicesPlaySystemSound(soundID);
// Now fade-out the image after a few seconds delay
sleep(3);
[self fadeout];
-(IBAction)fadein
{
[UIImageView beginAnimations:NULL context:nil];
[UIImageView setAnimationDuration:2];
[faceImage setAlpha:0.3];
[UIImageView commitAnimations];
}
-(IBAction)fadeout
{
[UIImageView beginAnimations:NULL context:nil];
[UIImageView setAnimationDuration:1];
[faceImage setAlpha:0];
[UIImageView commitAnimations];
}
I believe the problem is when you use “sleep(5)”. Using the sleep() function blocks the main thread so nothing can be done for that time period. It is exceedingly rare to use the sleep() function in Objective-C except maybe in some command-line utilities.
I recommend that you use an NSTimer instead of the sleep() function.
Hope this helps.
//Edit
Also if you really must use sleep(), you should instead use the sleepForTimeInterval: function of the NSThread class and get the rest of your code running on a secondary thread. Once again, I really don’t think you should use the sleep() function or any related functions.