iOS可以重用NSTimer

时间:2012-07-20 01:29:48

标签: ios ios5 ios4 timer nstimer

我想使用NSTimer(或者如果你有更好的建议)在设备拔出或未知时播放声音。但是,如果用户重新插入设备,声音应立即停止。

这是我的代码,但它似乎没有像我描述的那样表现,

- (void)currentBatteryState
{
    UIDevice *device = [UIDevice currentDevice];
    switch(device.batteryState) {
        case UIDeviceBatteryStateUnknown:
            currentBatteryStatusLabel.text = @"Unknown";
            if ([batteryControlTimer isValid]) {
                [batteryControlTimer invalidate];
                batteryControlTimer = [NSTimer scheduledTimerWithTimeInterval:2.5 target:self selector:@selector(playSound) userInfo:nil repeats:YES];
            } else {
                batteryControlTimer = [NSTimer scheduledTimerWithTimeInterval:2.5 target:self selector:@selector(playSound) userInfo:nil repeats:YES];
            }
            break;
        case UIDeviceBatteryStateUnplugged:
            currentBatteryStatusLabel.text = @"Unplugged";
            if ([batteryControlTimer isValid]) {
                [batteryControlTimer invalidate];
                batteryControlTimer = [NSTimer scheduledTimerWithTimeInterval:2.5 target:self selector:@selector(playSound) userInfo:nil repeats:YES];
            } else {
                batteryControlTimer = [NSTimer scheduledTimerWithTimeInterval:2.5 target:self selector:@selector(playSound) userInfo:nil repeats:YES];
            }
            break;
        case UIDeviceBatteryStateCharging:
            currentBatteryStatusLabel.text = @"Charging";
            [batteryControlTimer invalidate];
            break;
        case UIDeviceBatteryStateFull:
            currentBatteryStatusLabel.text = @"Full";
            [batteryControlTimer invalidate];
            break;
    }
}

- (void) playSound
{
    CFBundleRef mainBundle = CFBundleGetMainBundle();
    CFURLRef soundFileURLRef;
    soundFileURLRef = CFBundleCopyResourceURL(mainBundle, (CFStringRef) @"siren_1", CFSTR ("mp3"), NULL);
    UInt32 soundID;
    AudioServicesCreateSystemSoundID(soundFileURLRef, &soundID);
    AudioServicesPlaySystemSound(soundID);

}

谢谢

1 个答案:

答案 0 :(得分:3)

如果不满足条件,请勿播放任何声音,但不要使计时器无效。这样,即使条件没有达到一次,它也将继续按间隔射击。

所以:

- (void)playSound {
    if(conditionIsMet) {
        //code to play your sound
    }
}

编辑:

如果由于条件不满足而想要使声音停止的时间间隔,则只需要使定时器的时间间隔和声音的持续时间变小。