Environment: Mac OS Sonoma v14.4.1 Xcode 15.3
I'm new to iOS Swift development environment and trying to create a simple app to just return the current location address. I'm testing it with simulator iPhone 15 but the app is not returning any result. Please advise. Here is my code.
import SwiftUI
import CoreLocation
struct CurrentLocationView: View { @StateObject private var locationManager = LocationManager()
var body: some View {
VStack {
Text("Your Address:")
.font(.title2)
Text(locationManager.address ?? "Locating...")
.multilineTextAlignment(.center)
.padding()
}
.onAppear {
locationManager.requestAuthorization()
}
}
}
class LocationManager: NSObject, ObservableObject, CLLocationManagerDelegate { private let locationManager = CLLocationManager() @Published var address: String?
override init() {
super.init()
locationManager.delegate = self
locationManager.desiredAccuracy = kCLLocationAccuracyBest
}
func requestAuthorization() {
switch locationManager.authorizationStatus {
case .notDetermined:
locationManager.requestWhenInUseAuthorization()
case .authorizedWhenInUse, .authorizedAlways:
locationManager.startUpdatingLocation()
case .denied, .restricted:
// Handle denied or restricted authorization
print("Location services denied")
default:
break
}
}
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
guard let location = locations.first else { return }
let geocoder = CLGeocoder()
geocoder.reverseGeocodeLocation(location) { [weak self] placemarks, error in
guard let self = self, let placemark = placemarks?.first else { return }
// Extract address components
if let thoroughfare = placemark.thoroughfare, let locality = placemark.locality {
let address = "\(thoroughfare), \(locality)"
self.address = address
} else {
self.address = "Unable to determine address"
}
}
}
}
#Preview { CurrentLocationView() }