ios开发连续手机震动(kSystemSoundID_Vibrate连续震动)

时间:2021-05-03 18:19:12

最近做个功能,收到消息时要连续震动。之前都是调用AudioServicesPlaySystemSound(kSystemSoundID_Vibrate); ,只震动一次。 下面的代码是连续震动的,不过与设置的延时时间有有关哟。我设置了1秒,大概只震动2下。
技术上需要注意的是:使用单例实现了c++的函数回调。

加入#import AVFoundation/AVFoundation.h
@implementation Manager
+ (Manager *)shared
{
static Manager *sharedInstance = nil ;
static dispatch_once_t onceToken;
dispatch_once (& onceToken, ^ {
sharedInstance = [[self alloc] init];
});
return sharedInstance;
}
- (id)init
{
if (self = [super init]) {

}
return self;

}

  • (void)addVibrate {
    AudioServicesAddSystemSoundCompletion(kSystemSoundID_Vibrate, NULL, NULL, vibrateCallback, NULL);
    AudioServicesPlaySystemSound(kSystemSoundID_Vibrate);

}

  • (void)removeVibrate {

    [self performSelector:@selector(stopVibrate) withObject:nil afterDelay:1]; //设置1秒延时,
    }

void vibrateCallback(SystemSoundID sound,void * clientData) {
AudioServicesPlaySystemSound(kSystemSoundID_Vibrate); //震动

[[SettingManager shared] removeSoundID_Vibrate];

}
-(void)stopVibrate {
[NSObject cancelPreviousPerformRequestsWithTarget:self
selector:@selector(stopVibrateSound)
object:nil];
AudioServicesRemoveSystemSoundCompletion(kSystemSoundID_Vibrate);
}
@end