diff --git a/src/Uno.UWP/Devices/Sensors/SimpleOrientationSensor.cs b/src/Uno.UWP/Devices/Sensors/SimpleOrientationSensor.cs index 650ac4020195..d9aaa37b9a20 100644 --- a/src/Uno.UWP/Devices/Sensors/SimpleOrientationSensor.cs +++ b/src/Uno.UWP/Devices/Sensors/SimpleOrientationSensor.cs @@ -32,6 +32,9 @@ public static SimpleOrientationSensor GetDefault() private static partial SimpleOrientationSensor TryCreateInstance(); + partial void StartListeningOrientationChanged(); + + partial void StopListeningOrientationChanged(); #endregion diff --git a/src/Uno.UWP/Devices/Sensors/SimpleOrientationSensor.iOS.cs b/src/Uno.UWP/Devices/Sensors/SimpleOrientationSensor.iOS.cs index ace7f473cfb8..164755fc1dc2 100644 --- a/src/Uno.UWP/Devices/Sensors/SimpleOrientationSensor.iOS.cs +++ b/src/Uno.UWP/Devices/Sensors/SimpleOrientationSensor.iOS.cs @@ -22,6 +22,43 @@ public partial class SimpleOrientationSensor : null; } + partial void StartListeningOrientationChanged() + { + _motionManager ??= new(); + + if (!_motionManager.DeviceMotionAvailable) + { + if (this.Log().IsEnabled(LogLevel.Error)) + { + this.Log().Error("SimpleOrientationSensor failed to Start. CoreMotion is not available"); + } + } + + if (this.Log().IsEnabled(LogLevel.Information)) + { + this.Log().Info("DeviceMotion is available"); + } + + var operationQueue = (NSOperationQueue.CurrentQueue == null || NSOperationQueue.CurrentQueue == NSOperationQueue.MainQueue) + ? new NSOperationQueue() + : NSOperationQueue.CurrentQueue; + + _motionManager.DeviceMotionUpdateInterval = _updateInterval; + + _motionManager.StartDeviceMotionUpdates(operationQueue, OnMotionChanged); + } + + partial void StopListeningOrientationChanged() + { + if (_motionManager is null) + { + return; + } + + _motionManager.StopDeviceMotionUpdates(); + _motionManager.Dispose(); + _motionManager = null; + } partial void Initialize() { @@ -66,7 +103,7 @@ partial void Initialize() return; } - OnMotionChanged(motion); + OnMotionChanged(motion, error); }); } else // For iOS devices that don't support CoreMotion @@ -78,9 +115,31 @@ partial void Initialize() } } - private void OnMotionChanged(CMDeviceMotion motion) + private void OnMotionChanged(CMDeviceMotion? motion, NSError? error) { + // Motion and Error can be null: https://developer.apple.com/documentation/coremotion/cmdevicemotionhandler + if (error is not null) + { + if (this.Log().IsEnabled(LogLevel.Error)) + { + this.Log().Error($"SimpleOrientationSensor returned error when reading Device Motion updates. {error.Description}"); + } + + return; + } + + if (motion is null) + { + if (this.Log().IsEnabled(LogLevel.Error)) + { + this.Log().Error($"SimpleOrientationSensor failed read Device Motion updates."); + } + + return; + } + var orientation = ToSimpleOrientation(motion.Gravity.X, motion.Gravity.Y, motion.Gravity.Z, _threshold, _previousOrientation); + _previousOrientation = orientation; SetCurrentOrientation(orientation); }