我正在做一个POC,看看我是否能找到震动的强度。
class ViewController: UIViewController {
override func motionBegan(motion: UIEventSubtype, withEvent event: UIEvent) {
println("started shaking!")
}
override func motionEnded(motion: UIEventSubtype, withEvent event: UIEvent) {
println("ended shaking!")
}
}
我没有看到任何可以告诉我震动有多强烈的东西。就我而言,这次震动可能会持续几秒钟。
答案 0 :(得分:1)
您可以使用CoreMotion
框架阅读加速度计值的原始流。
答案 1 :(得分:1)
这是我在带有一些类变量和常量的didAccelerate回调中放入的代码:
UIAccelerationValue accelX, accelY, accelZ;
#define kAccelerometerFrequency 25 //Hz
#define kFilteringFactor 0.1
#define kMinShakeInterval 0.1
#define kShakeAccelerationThreshold 0.2
-(CMMotionManager*) motionManager{
if (_motionManager==nil) {
_motionManager=[[CMMotionManager alloc] init];
_motionManager.accelerometerUpdateInterval=1.0/25;
_motionManager.gyroUpdateInterval=1.0/25;
}
return _motionManager;
}
-(void) viewDidLoad{
[...]
[[self motionManager] startAccelerometerUpdatesToQueue:[NSOperationQueue currentQueue]
withHandler:^(CMAccelerometerData *accelerometerData, NSError *error) {
[self didAccelerate:accelerometerData.acceleration];
if(error){
NSLog(@"%@", error);
}
}];
[...]
}
- (void)didAccelerate:(CMAcceleration)acceleration{
UIAccelerationValue lenght, x, y, z;
accelX=acceleration.x*kFilteringFactor + accelX * (1.0 - kFilteringFactor);
accelY=acceleration.y*kFilteringFactor + accelY * (1.0 - kFilteringFactor);
accelZ=acceleration.z*kFilteringFactor + accelZ * (1.0 - kFilteringFactor);
x=acceleration.x - accelX;
y=acceleration.y - accelY;
z=acceleration.z - accelZ;
lenght=sqrt(x*x + y*y + z*z);
if (lenght>=kShakeAccelerationThreshold && (CFAbsoluteTimeGetCurrent()>lastTime + kMinShakeInterval)){
//execute shaking actions on main thread
}
}