Photo by Osman Rana on Unsplash

Detecting And Handling iOS Device Orientation Without KVO

Maxim Yurov
3 min readMay 5, 2019

When you are trying to find a solution, how to detect iOS device rotation changes, almost every answer on StackOverflow or any other site offers you to use Key-Value observing on changing interface orientation. And this is not an extremely bad way. We can implement it like this:

But, this approach has some big drawbacks and cons, the main two are:

  1. If a user will block orientation in settings (switch Portrait Lock Screen on), we will never receive rotation notifications. Our App is broken. For now, there is no possible way to detect rotation changes with Portrait Lock Screen turned on.
  2. Using KVO is, in my opinion, very “low-level approach”. Probability of making mistakes and writing hard-to-read code increases.

Ok, if I were you, I would ask:

“How you think we can detect and handle iOS device rotation changes in a more convenient and proper way?”

Use the CoreMotion Framework

Every Apple device has some equipment onboard, that can make iOS Developer life easier. Let's take a look to three of them, that are the main pillars of the CoreMotion framework:

  • Accelerometer
  • Gyroscope
  • Pedometer

In case that they are well-documented, I will just post a link to the developer documentation.

We can use Raw Accelerometer, Gyro, and etc. data to solve our problem. But Apple did almost everything for us. The has created special service, called “Device-Motion Service”, that, as they say:

Deliver acceleration, attitude, rotation, and magnetic field data that is adjusted for gravity and other forms of bias.

In our case, that is perfectly fit.

I have spent some hours to understand, how to properly handle every possible device orientation with this service’s output. Here is the code sample with my comments:

One of the problems, that I faced up with when I was working with a camera functionality on iOS using this approach was to “marry” proprietary interface rotation with device motion data. I was forced to synchronize them together to avoid lags and unexpected behavior of the interface.

If you have decided to create a camera app and want to get away from this problem note these rules:

  • Use device motion service every time and everywhere.
  • Switch off your default orientation changes using supportedOrientationMask
  • Icons and buttons need to just rotate depend on the device rotation but never move.

OR let iOS rotate the interface by herself. Not both.

That’s it! If you have some questions or additions, or if you’ve found a mistake — just let me know in comments, or find me on Twitter.

Thank you for reading this article and have a nice day!

--

--