TUIMotionManager.m 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. // Created by Tencent on 2023/06/09.
  2. // Copyright © 2023 Tencent. All rights reserved.
  3. #import "TUIMotionManager.h"
  4. #import <CoreMotion/CoreMotion.h>
  5. @import UIKit;
  6. @interface TUIMotionManager ()
  7. @property(nonatomic, strong) CMMotionManager *motionManager;
  8. @end
  9. @implementation TUIMotionManager
  10. - (instancetype)init {
  11. self = [super init];
  12. if (self) {
  13. _motionManager = [[CMMotionManager alloc] init];
  14. _motionManager.deviceMotionUpdateInterval = 1 / 15.0;
  15. if (!_motionManager.deviceMotionAvailable) {
  16. _motionManager = nil;
  17. return self;
  18. }
  19. __weak __typeof(self) weakSelf = self;
  20. [_motionManager startDeviceMotionUpdatesToQueue:[NSOperationQueue currentQueue]
  21. withHandler:^(CMDeviceMotion *motion, NSError *error) {
  22. __strong __typeof(weakSelf) strongSelf = weakSelf;
  23. [strongSelf performSelectorOnMainThread:@selector(handleDeviceMotion:) withObject:motion waitUntilDone:YES];
  24. }];
  25. }
  26. return self;
  27. }
  28. - (void)handleDeviceMotion:(CMDeviceMotion *)deviceMotion {
  29. double x = deviceMotion.gravity.x;
  30. double y = deviceMotion.gravity.y;
  31. if (fabs(y) >= fabs(x)) {
  32. if (y >= 0) {
  33. _deviceOrientation = UIDeviceOrientationPortraitUpsideDown;
  34. _videoOrientation = AVCaptureVideoOrientationPortraitUpsideDown;
  35. } else {
  36. _deviceOrientation = UIDeviceOrientationPortrait;
  37. _videoOrientation = AVCaptureVideoOrientationPortrait;
  38. }
  39. } else {
  40. if (x >= 0) {
  41. _deviceOrientation = UIDeviceOrientationLandscapeRight;
  42. _videoOrientation = AVCaptureVideoOrientationLandscapeRight;
  43. } else {
  44. _deviceOrientation = UIDeviceOrientationLandscapeLeft;
  45. _videoOrientation = AVCaptureVideoOrientationLandscapeLeft;
  46. }
  47. }
  48. }
  49. - (void)dealloc {
  50. [_motionManager stopDeviceMotionUpdates];
  51. }
  52. @end