我有一个简单的问题。我正在尝试检测用户何时摇动 iPhone。我有标准代码来检测运动,这没有问题。然而,在我的实际手机上进行测试时,我意识到你必须用力摇动设备才能触发运动检测。我想知道是否有办法实施一定程度的敏感性检查。例如,一种检测用户是否轻轻摇动设备或介于轻微摇动和剧烈摇动之间的方法。这将针对 iOS 7,因此任何未从旧版 iOS 版本中弃用的提示或建议将不胜感激。我已经完成了谷歌搜索,但尚未找到解决此问题的任何好的解决方案(如果有的话。)
Thanks!
-(void)motionEnded:(UIEventSubtype)motion withEvent:(UIEvent *)event
{
if(motion == UIEventSubtypeMotionShake)
{
//Detected motion, do something about it
//at this point.
}
}
-(BOOL)canBecomeFirstResponder
{
return YES;
}
-(void)viewDidAppear:(BOOL)animated
{
[super viewDidAppear:animated];
[self becomeFirstResponder];
}
-(void)viewWillDisappear:(BOOL)animated
{
[self resignFirstResponder];
[super viewWillDisappear:animated];
}
这是我找到的解决方案。这很有效,但您必须使用 deviceMotionUpdateInterval 时间值以及 AccelerationThreshold,这可能很难为实际的“轻微震动”与“拿起手机并将其移近您的脸等”获得良好的平衡行为...”可能有更好的方法,但这里是一个开始。在我的视图 didLoad 中我做了这样的事情:
#import <CoreMotion/CoreMotion.h> //do not forget to link the CoreMotion framework to your project
#define accelerationThreshold 0.30 // or whatever is appropriate - play around with different values
-(void)viewDidLoad
{
CMMotionManager *motionManager;
motionManager = [[CMMotionManager alloc] init];
motionManager.deviceMotionUpdateInterval = 1;
[motionManager startDeviceMotionUpdatesToQueue:[NSOperationQueue currentQueue] withHandler:^(CMDeviceMotion *motion, NSError *error)
{
[self motionMethod:motion];
}];
}
-(void)motionMethod:(CMDeviceMotion *)deviceMotion
{
CMAcceleration userAcceleration = deviceMotion.userAcceleration;
if (fabs(userAcceleration.x) > accelerationThreshold
|| fabs(userAcceleration.y) > accelerationThreshold
|| fabs(userAcceleration.z) > accelerationThreshold)
{
//Motion detected, handle it with method calls or additional
//logic here.
[self foo];
}
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)