DeviceMotion.swift 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. /*****************************************************************************
  2. * DeviceMotion.swift
  3. * VLC for iOS
  4. *****************************************************************************
  5. * Copyright (c) 2018 VideoLAN. All rights reserved.
  6. * $Id$
  7. *
  8. * Authors: Carola Nitz <caro # videolan.org>
  9. *
  10. *
  11. * Refer to the COPYING file of the official project for license.
  12. *****************************************************************************/
  13. import Foundation
  14. import CoreMotion
  15. @objc(VLCDeviceMotionDelegate)
  16. protocol DeviceMotionDelegate:NSObjectProtocol {
  17. func deviceMotionHasAttitude(deviceMotion:DeviceMotion, pitch:Double, yaw:Double, roll:Double)
  18. }
  19. @objc(VLCDeviceMotion)
  20. class DeviceMotion:NSObject {
  21. let motion = CMMotionManager()
  22. var referenceAttitude:CMAttitude? = nil
  23. @objc weak var delegate: DeviceMotionDelegate? = nil
  24. @objc func startDeviceMotion() {
  25. if motion.isDeviceMotionAvailable {
  26. motion.gyroUpdateInterval = 1.0 / 60.0 // 60 Hz
  27. motion.startDeviceMotionUpdates(using: .xTrueNorthZVertical, to: .main) {
  28. [weak self] (data, error) in
  29. guard let strongSelf = self, let data = data else {
  30. return
  31. }
  32. //We're using the initial angle of phone as 0.0.0 reference for all axis
  33. //we need to create a copy here, otherwise we just have a reference which is being changed in the next line
  34. if strongSelf.referenceAttitude == nil {
  35. strongSelf.referenceAttitude = data.attitude.copy() as? CMAttitude
  36. }
  37. // this line basically substracts the reference attitude so that we have yaw, pitch and roll changes in
  38. // relation to the very first angle
  39. data.attitude.multiply(byInverseOf: strongSelf.referenceAttitude!)
  40. let pitch = -(180/Double.pi)*data.attitude.pitch // -90; 90
  41. let yaw = -(180/Double.pi)*data.attitude.yaw // -180; 180
  42. let roll = -(180/Double.pi)*data.attitude.roll// -180; 180
  43. //print(pitch,yaw,roll)
  44. strongSelf.delegate?.deviceMotionHasAttitude(deviceMotion:strongSelf, pitch:pitch, yaw:yaw, roll:roll)
  45. }
  46. }
  47. }
  48. @objc func stopDeviceMotion() {
  49. if motion.isDeviceMotionActive {
  50. motion.stopDeviceMotionUpdates()
  51. self.referenceAttitude = nil
  52. }
  53. }
  54. }