I always get the user location not found error even though I have activated my location
import SwiftUI
import MapKit
import CoreLocation
class LocationManager: NSObject, ObservableObject, CLLocationManagerDelegate {
private let locationManager = CLLocationManager()
@Published var location: CLLocation? = nil
@Published var authorizationStatus: CLAuthorizationStatus? = nil
override init() {
super.init()
locationManager.delegate = self
locationManager.desiredAccuracy = kCLLocationAccuracyBest
locationManager.requestWhenInUseAuthorization()
locationManager.startUpdatingLocation()
}
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
guard let newLocation = locations.last else { return }
location = newLocation
print("Updated location: \(newLocation.coordinate.latitude), \(newLocation.coordinate.longitude)")
}
func locationManager(_ manager: CLLocationManager, didChangeAuthorization status: CLAuthorizationStatus) {
authorizationStatus = status
if status == .authorizedWhenInUse || status == .authorizedAlways {
locationManager.startUpdatingLocation()
}
}
}
private func sectionTitle(_ title: String) -> some View {
Text(title)
.font(.headline)
.fontWeight(.bold)
.padding(.bottom, 8)
}
private func openAppleMaps() {
let destinationLatitude: CLLocationDegrees = -6.914744
let destinationLongitude: CLLocationDegrees = 107.609810
guard let currentLocation = locationManager.location?.coordinate else {
print("Lokasi pengguna tidak ditemukan.")
return
}
let currentLatitude = currentLocation.latitude
let currentLongitude = currentLocation.longitude
// URL encode parameters
let urlString = "http://maps.apple.com/?saddr=\(currentLatitude),\(currentLongitude)&daddr=\(destinationLatitude),\(destinationLongitude)&dirflg=d"
guard let appleMapsUrl = URL(string: urlString) else {
print("URL tidak valid.")
return
}
// Open Apple Maps
UIApplication.shared.open(appleMapsUrl, options: [:]) { success in
if !success {
print("Gagal membuka Apple Maps.")
}
}
}