Skip to content

Instantly share code, notes, and snippets.

@chriship
Last active February 26, 2021 10:35
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save chriship/3b5bfa01462b5267072ef66d29b22cd9 to your computer and use it in GitHub Desktop.
Save chriship/3b5bfa01462b5267072ef66d29b22cd9 to your computer and use it in GitHub Desktop.
LocationTracker
//
// Tracker.swift
// LocationTracker
//
// Created by Chris Hipgrave on 25/02/2021.
//
import CoreLocation
class Tracker : NSObject, CLLocationManagerDelegate {
static let shared = Tracker()
var locationManager: CLLocationManager?
var updateLabel: (() -> Void)?
var heading: Double = 0 {
didSet {
updateLabel?()
}
}
override init() {
super.init()
self.locationManager = CLLocationManager()
self.locationManager?.delegate = self
self.locationManager?.headingFilter = 0.1
self.locationManager?.requestAlwaysAuthorization()
}
func startTracking() {
locationManager?.startUpdatingHeading()
}
func locationManager(_ manager: CLLocationManager, didChangeAuthorization status: CLAuthorizationStatus) {
if status == .authorizedAlways || status == .authorizedWhenInUse {
if CLLocationManager.headingAvailable() {
self.startTracking()
}
}
}
func locationManager(_ manager: CLLocationManager, didUpdateHeading newHeading: CLHeading) {
self.heading = newHeading.trueHeading
print(newHeading.trueHeading)
}
}
import UIKit
class ViewController: UIViewController {
@IBOutlet weak var label: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
Tracker.shared.startTracking()
Tracker.shared.updateLabel = updateLabel
}
func updateLabel(){
label.text = String(describing: Tracker.shared.heading)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment