Lior Colina
Lior Colina

Reputation: 1

How to print compass orientation on Xcode?

I am very new to coding in general and have been following lots of tutorials to get where I am right now. I followed this other question of stackoverflow: Finding the compass orientation of an iPhone in swift

Following the code in each answer, nothing is being printed. This is my code:

import UIKit
import CoreLocation

class PointingViewController: UIViewController, CLLocationManagerDelegate {
    var locationManager: CLLocationManager = CLLocationManager()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        locationManager.delegate = self
}

    func locationManager(_ manager: CLLocationManager, didUpdateHeading newHeading: CLHeading) {
        print(newHeading.magneticHeading)
    }

   @IBAction func firstButtonPressed(_ sender: Any) {
        locationManager.startUpdatingLocation()
        locationManager.startUpdatingHeading()
}

Ideally, the compass orientation is recorded whenever the button is pressed. I have tried putting the .startUpdatingLocation() and .startUpdatingHeading in the viewDidLoad() function, but no change occurs.

Is there a better way to accomplish what I desire?

Upvotes: -1

Views: 417

Answers (2)

de.
de.

Reputation: 8527

You should search for a proper tutorial for this online. I will give you some pointers to get you started, but please do your own research.
You have to request permission first. Add this to your viewDidLoad

locationManager.requestAlwaysAuthorization()

Also implement the delegate method

func locationManager(_ manager: CLLocationManager, didChangeAuthorization status: CLAuthorizationStatus) {
    // start requesting heading information if you are authorized. 
}

And deal with the different states.

Also you may need to add a permission entry in your Info.plist, but I am not sure it is required for heading.

Upvotes: 0

Shadowrun
Shadowrun

Reputation: 3867

Code looks alright apart from you not doing all the things the documentation says you need to do, like check isHeadingAvailable etc. Docs say:

If heading information is not supported, calling this method has no effect and does not result in the delivery of events to your delegate.

Implement locationManager(_:didFailWithError:) is also a good plan if things aren't working.

Have you done the necessary things regarding Location permissions documented in "Adding Location Services to Your App"

Upvotes: 0

Related Questions