I am trying to display user location coordinates on screen but nothing shows up when i run the app even though i can see coordinates in console. And the second problem i have is when i press the stop button the location updates do not stop.
LocationManager:
import Foundation
import CoreLocation
class LocationManager: NSObject, ObservableObject, CLLocationManagerDelegate{
let locationManager = CLLocationManager()
@Published var location: CLLocationCoordinate2D?
override init(){
super.init()
locationManager.delegate = self
}
func startTracking() {
locationManager.requestAlwaysAuthorization()
locationManager.desiredAccuracy = kCLLocationAccuracyBest
locationManager.distanceFilter = kCLDistanceFilterNone
locationManager.allowsBackgroundLocationUpdates = true
locationManager.startUpdatingLocation()
}
func stopTracking() {
print("stop test")
locationManager.stopUpdatingLocation()
locationManager.allowsBackgroundLocationUpdates = false
}
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
let tempLocation = locations.last?.coordinate
print(tempLocation)
DispatchQueue.main.async {
self.location = tempLocation
}
}
}
View:
import SwiftUI
struct ContentView: View {
@StateObject var locationManager = LocationManager()
var body: some View {
VStack{
startLocationTrackingButton()
stopLocationTrackingButton()
if let location = locationManager.location {
Text("Your location: \(location.latitude), \(location.longitude)")
}
}
}
}
struct startLocationTrackingButton: View{
@StateObject var locationManager = LocationManager()
var body: some View{
Button("START"){
locationManager.startTracking()
}
}
}
struct stopLocationTrackingButton: View{
@StateObject var locationManager = LocationManager()
var body: some View{
Button("STOP"){
locationManager.stopTracking()
}
}
}
Thanks for help!