Contenidos
Permiso para acceder a la localización GPS (Allow access to location on Apple Watch)
Código de la aplicación para Apple Watch que muestra la posición GPS cuando se pulsa a un botón
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 |
import SwiftUI import CoreLocation class LocationManager: NSObject, ObservableObject, CLLocationManagerDelegate { private var locationManager = CLLocationManager() @Published var locationText = "Ubicación: No disponible" override init() { super.init() locationManager.delegate = self locationManager.desiredAccuracy = kCLLocationAccuracyNearestTenMeters } func requestLocation() { locationManager.requestWhenInUseAuthorization() locationManager.startUpdatingLocation() } func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) { guard let location = locations.last else { return } let latitude = location.coordinate.latitude let longitude = location.coordinate.longitude locationText = "Ubicación: Latitud \(latitude), Longitud \(longitude)" } func locationManager(_ manager: CLLocationManager, didFailWithError error: Error) { locationText = "Error al obtener la ubicación" } } struct ContentView: View { @StateObject private var locationManager = LocationManager() var body: some View { VStack { Text(locationManager.locationText) .padding() Button("Obtener Ubicación") { locationManager.requestLocation() } .padding() } } } @main struct pruebaApp: App { var body: some Scene { WindowGroup { ContentView() } } } |