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; ...

Get Programming iOS 6, 3rd Edition 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.