RCTSensorOrientationChecker.m
3.06 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
//
// RCTSensorOrientationChecker.m
// RCTCamera
//
// Created by Radu Popovici on 24/03/16.
//
//
#import "RCTSensorOrientationChecker.h"
#import <CoreMotion/CoreMotion.h>
@interface RCTSensorOrientationChecker ()
@property (strong, nonatomic) CMMotionManager * motionManager;
@property (strong, nonatomic) RCTSensorCallback orientationCallback;
@end
@implementation RCTSensorOrientationChecker
- (instancetype)init
{
self = [super init];
if (self) {
// Initialization code
self.motionManager = [[CMMotionManager alloc] init];
self.motionManager.accelerometerUpdateInterval = 0.2;
self.motionManager.gyroUpdateInterval = 0.2;
self.orientationCallback = nil;
}
return self;
}
- (void)dealloc
{
[self pause];
}
- (void)resume
{
__weak __typeof(self) weakSelf = self;
[self.motionManager startAccelerometerUpdatesToQueue:[NSOperationQueue new]
withHandler:^(CMAccelerometerData *accelerometerData, NSError *error) {
if (!error) {
self.orientation = [weakSelf getOrientationBy:accelerometerData.acceleration];
}
if (self.orientationCallback) {
self.orientationCallback(self.orientation);
}
}];
}
- (void)pause
{
[self.motionManager stopAccelerometerUpdates];
}
- (void)getDeviceOrientationWithBlock:(RCTSensorCallback)callback
{
__weak __typeof(self) weakSelf = self;
self.orientationCallback = ^(UIInterfaceOrientation orientation) {
if (callback) {
callback(orientation);
}
weakSelf.orientationCallback = nil;
[weakSelf pause];
};
[self resume];
}
- (UIInterfaceOrientation)getOrientationBy:(CMAcceleration)acceleration
{
if(acceleration.x >= 0.75) {
return UIInterfaceOrientationLandscapeLeft;
}
if(acceleration.x <= -0.75) {
return UIInterfaceOrientationLandscapeRight;
}
if(acceleration.y <= -0.75) {
return UIInterfaceOrientationPortrait;
}
if(acceleration.y >= 0.75) {
return UIInterfaceOrientationPortraitUpsideDown;
}
return [[UIApplication sharedApplication] statusBarOrientation];
}
- (AVCaptureVideoOrientation)convertToAVCaptureVideoOrientation:(UIInterfaceOrientation)orientation
{
switch (orientation) {
case UIInterfaceOrientationPortrait:
return AVCaptureVideoOrientationPortrait;
case UIInterfaceOrientationPortraitUpsideDown:
return AVCaptureVideoOrientationPortraitUpsideDown;
case UIInterfaceOrientationLandscapeLeft:
return AVCaptureVideoOrientationLandscapeLeft;
case UIInterfaceOrientationLandscapeRight:
return AVCaptureVideoOrientationLandscapeRight;
default:
return 0; // unknown
}
}
@end