我正在做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!")
}
}我看不出有什么东西能告诉我摇晃有多强烈。在我的例子中,这种震动可能是持续几秒钟的事件。
发布于 2015-05-05 18:28:06
这是我在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
}
}发布于 2015-05-05 17:19:48
您可以使用CoreMotion框架读取加速度计值的原始流。
https://stackoverflow.com/questions/30058947
复制相似问题