Sitemap

How to Request Device Motion and Orientation Permission in iOS 13

The Return of the Gyroscope

2 min readSep 19, 2019

--

Image

I’ve covered the issue of Apple turning device orientation and motion off by default since iOS 12.2 a few times on this Medium. Well, with iOS 13 finally reaching devices today, we now have a permission API we can use to gain access to these events, the same way we would the Camera or GPS. The permissions API is a known user pattern and it works great. 👍🏻

Integrating this into your web app couldn’t be simpler. Just be sure to call the associated requestPermission() method from a click event.

Get Lee Martin’s stories in your inbox

Join Medium for free to get updates from this writer.

Here’s the code for devicemotion events:

DeviceMotionEvent.requestPermission()
.then(response => {
if (response == 'granted') {
window.addEventListener('devicemotion', (e) => {
// do something with e
})
}
})
.catch(console.error)

And the equivalent for deviceorientation events:

DeviceOrientationEvent.requestPermission()
.then(response => {
if (response == 'granted') {
window.addEventListener('deviceorientation', (e) => {
// do something with e
})
}
})
.catch(console.error)

Simple enough. If you’re planning on providing fallbacks for non iOS 13 devices, you can simple check to see if the requestPermission method exists with a typeof call. Just swap DeviceMotionEvent with DeviceOrientationEvent as needed.

if (typeof DeviceMotionEvent.requestPermission === 'function') {
// iOS 13+
} else {
// non iOS 13+
}

I can’t wait to revisit my knighting app.

Thanks for reading!

--

--

Lee Martin
Lee Martin

Written by Lee Martin

Netmaker. Playing the Internet in your favorite band for two decades. Previously Silva Artist Management, SoundCloud, and Songkick.

Responses (10)