请参阅UIDevice类参考中的使用接近传感器.那么你:
启用它:
UIDevice *device = [UIDevice currentDevice];
device.proximityMonitoringEnabled = YES;
Run Code Online (Sandbox Code Playgroud)检查是否成功启用; UIDeviceProximityStateDidChangeNotification如果成功,请遵守通知; 如果没有,您的设备可能无法使用:
if (device.proximityMonitoringEnabled)
{
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(handleProximityChange:)
name:UIDeviceProximityStateDidChangeNotification
object:nil];
}
else
{
// device not capable
}
Run Code Online (Sandbox Code Playgroud)写下你的选择器:
- (void)handleProximityChange:(NSNotification *)notification
{
NSLog(@"%s proximityState=%d", __FUNCTION__, [[UIDevice currentDevice] proximityState]);
}
Run Code Online (Sandbox Code Playgroud)为了检测用户是否将其握在脸上,我可能会将接近传感器与其结合CMMotionManager并查看gravity属性以查看他们是否几乎垂直握住手机.因此,定义一些类属性:
@property (nonatomic, strong) CMMotionManager *motionManager;
@property (nonatomic, strong) NSOperationQueue *deviceQueue;
Run Code Online (Sandbox Code Playgroud)
然后你可以启动CMMotionManager,查看设备是否处于垂直位置:
self.deviceQueue = [[NSOperationQueue alloc] init];
self.motionManager = [[CMMotionManager alloc] init];
self.motionManager.deviceMotionUpdateInterval = 5.0 / 60.0;
UIDevice *device = [UIDevice currentDevice];
[self.motionManager startDeviceMotionUpdatesUsingReferenceFrame:CMAttitudeReferenceFrameXArbitraryZVertical
toQueue:self.deviceQueue
withHandler:^(CMDeviceMotion *motion, NSError *error)
{
BOOL vertical = (motion.gravity.z > -0.4 && motion.gravity.z < 0.4 & motion.gravity.y < -0.7);
if ((vertical && !device.proximityMonitoringEnabled) || (!vertical && device.proximityMonitoringEnabled))
{
device.proximityMonitoringEnabled = vertical;
}
}];
Run Code Online (Sandbox Code Playgroud)
这些gravity阈值是否有意义是有点主观的.您也可以,而不是仅仅查看手机是否大致垂直握持,查看其他加速度计数据(例如,他们是否提升了对象).似乎有很多方法可以给猫皮肤.
| 归档时间: |
|
| 查看次数: |
1668 次 |
| 最近记录: |