Last active
February 26, 2021 10:35
-
-
Save chriship/3b5bfa01462b5267072ef66d29b22cd9 to your computer and use it in GitHub Desktop.
LocationTracker
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// | |
// 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) | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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