PCSDeviceOrientationManager.m 2.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102
  1. //
  2. // PCSDeviceOrientationManager.m
  3. // LenzSDK
  4. //
  5. // Created by lr on 2023/5/12.
  6. //
  7. #import "PCSDeviceOrientationManager.h"
  8. #import <CoreMotion/CoreMotion.h>
  9. static const float sensitive = 0.77;
  10. @interface PCSDeviceOrientationManager () {
  11. CMMotionManager *_motionManager;
  12. }
  13. @end
  14. @implementation PCSDeviceOrientationManager
  15. - (instancetype)initWithDelegate:(id<PCSDeviceOrientationDelegate>)delegate {
  16. self = [super init];
  17. if (self) {
  18. _delegate = delegate;
  19. }
  20. return self;
  21. }
  22. - (void)startMonitor {
  23. [self start];
  24. }
  25. - (void)stop {
  26. [_motionManager stopDeviceMotionUpdates];
  27. }
  28. //陀螺仪 每隔一个间隔做轮询
  29. - (void)start{
  30. if (_motionManager == nil) {
  31. _motionManager = [[CMMotionManager alloc] init];
  32. }
  33. _motionManager.deviceMotionUpdateInterval = 1/40.f;
  34. if (_motionManager.deviceMotionAvailable) {
  35. [_motionManager startDeviceMotionUpdatesToQueue:[NSOperationQueue currentQueue]
  36. withHandler: ^(CMDeviceMotion *motion, NSError *error){
  37. [self performSelectorOnMainThread:@selector(deviceMotion:) withObject:motion waitUntilDone:YES];
  38. }];
  39. }
  40. }
  41. - (void)deviceMotion:(CMDeviceMotion *)motion{
  42. double x = motion.gravity.x;
  43. double y = motion.gravity.y;
  44. if (y < 0 ) {
  45. if (fabs(y) > sensitive) {
  46. if (self.currentDirection != TgDirectionPortrait) {
  47. self.currentDirection = TgDirectionPortrait;
  48. if ([self.delegate respondsToSelector:@selector(directionChange:)]) {
  49. [self.delegate directionChange:self.currentDirection];
  50. }
  51. }
  52. }
  53. }else {
  54. if (y > sensitive) {
  55. if (self.currentDirection != TgDirectionDown) {
  56. self.currentDirection = TgDirectionDown;
  57. if ([self.delegate respondsToSelector:@selector(directionChange:)]) {
  58. [self.delegate directionChange:self.currentDirection];
  59. }
  60. }
  61. }
  62. }
  63. if (x < 0 ) {
  64. if (fabs(x) > sensitive) {
  65. if (self.currentDirection != TgDirectionLeft) {
  66. self.currentDirection = TgDirectionLeft;
  67. if ([self.delegate respondsToSelector:@selector(directionChange:)]) {
  68. [self.delegate directionChange:self.currentDirection];
  69. }
  70. }
  71. }
  72. }else {
  73. if (x > sensitive) {
  74. if (self.currentDirection != TgDirectionRight) {
  75. self.currentDirection = TgDirectionRight;
  76. if ([self.delegate respondsToSelector:@selector(directionChange:)]) {
  77. [self.delegate directionChange:self.currentDirection];
  78. }
  79. }
  80. }
  81. }
  82. }
  83. @end