Finding the compass orientation of an iPhone in swift

Matt Spoon picture Matt Spoon · Jun 8, 2015 · Viewed 15k times · Source

I'm trying to make an app which is similar to a compass, but with notable differences, however, they are not important. What I need to know is: how can I get the iPhone to give me the compass orientation (i.e. 0 degrees for north) regardless of the phone's orientation (i.e. It will give the same reading if it is lying flat on a table or portrait in someone's hand if it is pointing the same way)

TL;DR How can I get an iPhone's rotation around the y axis which updates every second or so.

Answer

Reming Hsu picture Reming Hsu · Jun 8, 2015

import CoreLocation

class ViewController: UIViewController ,CLLocationManagerDelegate {

    var lm:CLLocationManager!

    override func viewDidLoad() {
        super.viewDidLoad()

        lm = CLLocationManager()
        lm.delegate = self

        lm.startUpdatingHeading()
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
    }

    func locationManager(manager: CLLocationManager!, didUpdateHeading newHeading: CLHeading!) {
        println(newHeading.magneticHeading)
    }
}

You can get more information from https://developer.apple.com/library/ios/documentation/CoreLocation/Reference/CLHeading_Class/