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 |
extension ViewController: CLLocationManagerDelegate { func determineMyCurrentLocation() { var locationManager: CLLocationManager = CLLocationManager() locationManager.delegate = self locationManager.desiredAccuracy = kCLLocationAccuracyBest locationManager.requestAlwaysAuthorization() if CLLocationManager.locationServicesEnabled() { locationManager.startUpdatingLocation() //locationManager.startUpdatingHeading() } } func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) { var userLocation: CLLocation = locations[0] as CLLocation // Call stopUpdatingLocation() to stop listening for location updates, // other wise this function will be called every time when user location changes. // manager.stopUpdatingLocation() // print("user latitude = \(userLocation?.coordinate.latitude)") // print("user longitude = \(userLocation?.coordinate.longitude)") } func locationManager(_ manager: CLLocationManager, didFailWithError error: Error) { print("Error \(error)") } } |
Add into info.plist
1 2 3 4 5 |
<key>NSLocationAlwaysUsageDescription</key> <string>Will you allow this app to always know your location?</string> <key>NSLocationWhenInUseUsageDescription</key> <string>Do you allow this app to know your current location?</string> |