Skip to content

Instantly share code, notes, and snippets.

@piemonte
Created Sep 24, 2022
Embed
What would you like to do?
//
// DirectionalView.swift
//
import UIKit
import Foundation
import CoreLocation.CLLocation
import Position
public final class DirectionalView: UIView {
// MARK: - ivars
private lazy var _indicator: UIImageView = {
let view = UIImageView(image: UIImage(named: "direction_indicator")?.withRenderingMode(UIImage.RenderingMode.alwaysTemplate))
view.translatesAutoresizingMaskIntoConstraints = false
view.tintColor = .black
return view
}()
private var _location: CLLocation?
private var _accuracyAnimator: UIViewPropertyAnimator?
// MARK: - object lifecycle
override public init(frame: CGRect) {
super.init(frame: frame)
setup()
}
public required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
setup()
}
deinit {
LocationManager.shared.removeHeadingObserver(self)
}
}
extension DirectionalView {
private func setup() {
addSubview(_indicator)
_accuracyAnimator = UIViewPropertyAnimator(duration: 0.15, curve: .easeInOut) {
self._indicator.alpha = 0.25
}
_indicator.alpha = 0
}
public func config(_ targetLocation: CLLocation) {
_location = targetLocation
LocationManager.shared.addHeadingObserver(self)
UIView.animate(withDuration: 0.15, delay: 0, options: .curveEaseIn) {
self._indicator.alpha = 1
} completion: { _ in
}
}
}
// MARK: - LocationManagerHeadingObserver
extension DirectionalView: LocationManagerHeadingObserver {
public func locationManager(_ locationManager: LocationManager, didUpdateHeading heading: CLHeading) {
guard let targetLocation = _location else { return }
guard let currentLocation = LocationContext.shared.lastLocation else { return // fade }
if heading.headingAccuracy >= 0,
let angle = currentLocation.bearingInRadians(toLocation: targetLocation, heading: heading) {
UIView.animate(withDuration: 0.25) { [weak self] in
guard let self = self else { return }
self._indicator.transform = CGAffineTransform(rotationAngle: angle)
}
} else {
// fade indicator (not accurate)
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment