我想使用NSTimer(或者如果您有更好的建议)在设备拔出或未知时播放声音。但是,如果用户重新插入设备,声音应立即停止。iOS可以重复使用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);
}
谢谢
定义*重用*。 – 2012-07-20 01:31:33
使用相同的变量(batteryControlTimer)而不必创建一个新变量。 batteryControlTimer在h文件中,我们综合了实现文件中的属性。 – 2012-07-20 02:00:02