iOS 我们可以重用 NSTimer

标签 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);

}

谢谢

最佳答案

如果不满足条件,则不播放任何声音,但不使计时器失效。这样即使条件一次都没有满足,它也会在间隔内继续触发。

所以:

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

编辑:

如果你想让声音停止的时间间隔因为条件不满足,那么你只需要把定时器的时间间隔和声音的持续时间调小即可。

关于iOS 我们可以重用 NSTimer,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11571658/

相关文章:

ios - SwiftUI View 不更新

ios - UIButton 边框在被选中时改变粗细

iphone - popViewController 动画在 iOS 5 中不起作用

iphone - 如何正确应用 Core Image 滤镜

iphone - 是否可以检测到状态栏时钟上的 "Minute"何时发生变化?

iphone - UITableView 未正确对齐

opengl-es - 如何将 OpenGL ES 纹理转换为 CIImage

iphone - 子类化 MKAnnotationView 并重写 setDragState

iphone - 键盘触发通知以及默认通知

iOS 7 +'s "再见快照”