Heading
For appropriately equipped devices, Core Location also supports use of the magnetometer to determine which way the device is facing (its heading). Although this information is accessed through a location manager, you do not need location services to be turned on, nor your app to be authorized, merely to use the magnetometer to report the device’s orientation with respect to magnetic north; but you do need those things in order to report true north, as this depends on the device’s location.
As with location, you’ll first check that the desired feature is available (headingAvailable); then you’ll instantiate and configure the location manager, and call startUpdatingHeading. The delegate will be sent locationManager:didUpdateHeading:. Heading values are reported as a CLHeading; recall that this involves degrees (not radians) clockwise from the reference direction.
In this example, I’ll use the device as a compass. The headingFilter setting is to prevent us from being bombarded constantly with readings. For best results, the device should probably be held level (like a tabletop, or a compass); the reported heading will be the direction in which the top of the device (the end away from the Home button) is pointing:
BOOL ok = [CLLocationManager headingAvailable]; if (!ok) { NSLog(@"drat"); return; } CLLocationManager* lm = [CLLocationManager new]; self.locman = lm; self.locman.delegate = self; self.locman.headingFilter = 3; self.locman.headingOrientation = CLDeviceOrientationPortrait; ...Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access