首先声明,这个方法是网上一个朋友发给我的。非自己原创。https://github.com/dustturtle/ 这是他的github地址。
首先,创建了单例。直接贴代码了。
ShakeInstance.h中:
#import#import@interface ShakeInstance : NSObject
//单例接口
+ (ShakeInstance *)shareInstance;
- (void)vibrateCallback;
- (void) triggerShake;
@end
ShakeInstance.m中:
#import "ShakeInstance.h"
@implementation ShakeInstance
static ShakeInstance *shakeInstance = nil;
//单例接口
+ (ShakeInstance *)shareInstance
{
if (!shakeInstance)
{
@synchronized(self)
{
if (!shakeInstance)
{
shakeInstance = [[ShakeInstance alloc] init];
}
}
}
return shakeInstance;
}
- (void)vibrateCallback
{
// 此处设置震动间隔
[self performSelector:@selector(triggerShake) withObject:nil afterDelay:1];//设置震动之间的间隔时间
}
- (void)triggerShake
{
SystemSoundID soundID = kSystemSoundID_Vibrate;
AudioServicesPlaySystemSound (soundID);
}
@end
ViewController.m中调用:
#import "ViewController.h"
#import "ShakeInstance.h"
@interface ViewController ()
- (IBAction)stopShake:(id)sender;
- (IBAction)startShake:(id)sender;
@end
@implementation ViewController
void systemAudioCallback(SystemSoundID soundId, void *clientData)
{
[[ShakeInstance shareInstance] vibrateCallback];
}
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
- (IBAction)stopShake:(id)sender
{
AudioServicesRemoveSystemSoundCompletion(kSystemSoundID_Vibrate);//移除停止震动
[NSObject cancelPreviousPerformRequestsWithTarget:[ShakeInstance shareInstance]
selector:@selector(triggerShake)
object:nil];
}
- (IBAction)startShake:(id)sender
{
AudioServicesAddSystemSoundCompletion(kSystemSoundID_Vibrate, NULL, NULL, systemAudioCallback, NULL);
SystemSoundID soundID = kSystemSoundID_Vibrate;
AudioServicesPlaySystemSound (soundID);
}
@end'