Chapter 22. Sensors

A device may contain hardware for sensing the world around itself — where it is located, how it is oriented, how it is moving.

Information about the device’s current location and how that location is changing over time using its WiFi, cellular networking, and GPS capabilities, along with information about the device’s orientation relative to north using its magnetometer, is provided through the Core Location framework.

Information about the device’s change in speed and attitude using its accelerometer is provided through the UIEvent class (for device shake) and the Core Motion framework, which provides increased accuracy by incorporating the device’s gyroscope, if it has one, as well as the magnetometer. In addition, the device may have an extra chip that analyzes and records the user’s activity, such as walking or running, and even a barometer that reports changes in altitude; the Core Motion framework provides access to this information as well.

A challenge associated with writing code that takes advantage of the sensors is that different devices have different hardware. If you don’t want to impose stringent restrictions on what devices your app will run on in the first place (UIRequiredDeviceCapabilities in the Info.plist), your code must be prepared to fail gracefully, perhaps providing a subset of your app’s full capabilities, when it turns out that the current device lacks certain features.

Even on a device that has the necessary hardware, certain sensors ...

Get Programming iOS 14 now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.