Notifies changes in device orientation using CoreMotion on iOS, sending updates through NotificationCenter. It enables detection of device orientation and interface orientation while keeping the UI orientation locked, such as when the device is restricted to 'Portrait Orientation Lock'. This makes it possible to respond to orientation changes even when the UI itself does not rotate.
This codes are under ARC.
These frameworks are needed.
CoreMotion.framework CoreGraphics.framework
MotionOrientation.sharedInstance().start()MotionOrientationChangedNotification, when the device orientation changed.
@objc private func deviceOrientationDidChange(notification: NSNotification) {
// You can get it from userInfo with key kMotionOrientationDeviceOrientationKey
if let userInfo = notification.userInfo,
let rawValue = userInfo[kMotionOrientationDeviceOrientationKey] as? NSNumber,
let orientation = UIDeviceOrientation(rawValue: rawValue.intValue) {
print("new device orientation from userInfo: " + orientation)
}
// or get it from sharedInstance
print("new device orientation from sharedInstance: " + MotionOrientation.sharedInstance().deviceOrientation);
}MotionOrientationInterfaceOrientationChangedNotification, just when the interface orientation changed.
@objc private func interfaceOrientationDidChange(notification: NSNotification) {
// You can get it from userInfo with key kMotionOrientationInterfaceOrientationKey
if let userInfo = notification.userInfo,
let rawValue = userInfo[kMotionOrientationInterfaceOrientationKey] as? NSNumber,
let orientation = UIInterfaceOrientation(rawValue: rawValue.intValue) {
print("new interface orientation from userInfo: " + orientation)
}
// or get it from sharedInstance
print("new interface orientation from sharedInstance: " + MotionOrientation.sharedInstance().interfaceOrientation);
}private func printOrientations() {
print("current device orientation: " + MotionOrientation.sharedInstance().deviceOrientation)
print("current interface orientation: " + MotionOrientation.sharedInstance().interfaceOrientation)
}- will stop when the app enters background.
- will restart when the app becomes active.
You can manually stop or restart it to save energe in specific situations.
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
MotionOrientation.sharedInstance().start() // it's okay to call start repeatedly
}override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
MotionOrientation.sharedInstance().stop() // disables MotionOrientation until manually started
}- turns on when
ProcessInfo.processInfo.isLowPowerModeEnabled. - turns on when
ProcessInfo.processInfo.thermalStateis NOT in (.nominal,.fair)
You can manually turn on of off the Low Energe Mode.
MotionOrientation.sharedInstance().setLowEnergeModeForcely(true)