I want to detect face up position with sensor information. If position of the iPhone is face up, the button on the screen named as btnOpen should be seem, otherwise the button should be hidden. I'm checking z values and interval [-0.8, -1.0] Z values changing correctly but btnOpen.hidden = YES or NO working first time then doesn't working. I created a label to print z values on screen but it writes first z valu and the value didn't change. What is the problem ? How can I fix this problem ?
NSOperationQueue *theQueue = [[NSOperationQueue alloc] init];
returnedData = [[CMAccelerometerData alloc] init];
motionManager = [[CMMotionManager alloc] init];
[motionManager startAccelerometerUpdatesToQueue:theQueue withHandler:^(CMAccelerometerData *accelerometerData, NSError *error) {
returnedData = motionManager.accelerometerData;
float z = returnedData.acceleration.z;
NSLog(@"Z: %f", z);
if(z > -1.0 && z < -0.8 ){
btnOpen.hidden = NO;
}
else{
btnOpen.hidden = YES;
}
- (void)viewDidLoad {
[[UIDevice currentDevice] beginGeneratingDeviceOrientationNotifications];
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(orientationChanged:) name:UIDeviceOrientationDidChangeNotification object:[UIDevice currentDevice]];
}
- (void)orientationChanged:(NSNotification *)note{
UIDevice * device = note.object;
// NSLog(@"rotation main %d ",device.orientation;);
switch(device.orientation){
case 1:
//Portrait
break;
case 4:
//landscape right
break;
case 3:
//landscape left
break;
default:
//other orientations
break;
};
}
I solved the problem with using Scheduled Timer. Every 0.5 second calling method below and working.
- (void)viewDidLoad {
[super viewDidLoad];
theQueue = [[NSOperationQueue alloc] init];
returnedData = [[CMAccelerometerData alloc] init];
motionManager = [[CMMotionManager alloc] init];
[NSTimer scheduledTimerWithTimeInterval:0.5f
target:self selector:@selector(checkPhonePosition:) userInfo:nil repeats:YES];
}
-(void)checkPhonePosition:(NSTimer *)timer {
[motionManager startAccelerometerUpdatesToQueue:theQueue withHandler:^(CMAccelerometerData *accelerometerData, NSError *error) {
returnedData = motionManager.accelerometerData;
z = returnedData.acceleration.z;
NSLog(@"Z: %f", z);
}];
if(z > -1.0 && z < -0.8 ){
btnOpen.hidden = NO;
}
else{
btnOpen.hidden = YES;
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.