Last active
January 19, 2019 21:19
-
-
Save GoranLilja/685934c265088d38dc59e74993b49466 to your computer and use it in GitHub Desktop.
Getting the user's location
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import UIKit | |
import CoreLocation | |
class ViewController: UIViewController { | |
let locationManager = CLLocationManager() | |
override func viewDidLoad() { | |
super.viewDidLoad() | |
locationManager.delegate = self | |
locationManager.requestWhenInUseAuthorization() | |
} | |
} | |
extension ViewController: CLLocationManagerDelegate { | |
func locationManager(_ manager: CLLocationManager, didChangeAuthorization status: CLAuthorizationStatus) { | |
switch status { | |
case .authorizedAlways, | |
.authorizedWhenInUse: | |
print("We're allowed to get the user's location.") | |
if let location = manager.location { | |
print("Current location: \(location.coordinate.longitude), \(location.coordinate.latitude)") | |
} | |
// I suppose the following line isn't needed if you don't want to get location updates. | |
// If you remove the line below, you can remove locationManager(_:, didUpdateLocations:) (lines 36-39) as well. | |
locationManager.startUpdatingLocation() | |
case .denied: | |
print("The user denied access. He/she needs to go to Settings to allow it.") | |
case .restricted: | |
print("The user doesn't have the permissions to allow the app to see locations. Maybe the user is a child with limited permissions.") | |
case .notDetermined: | |
print("The user has not decided yet.") | |
} | |
} | |
// The following function is only needed if locationManager.startUpdatingLocation() is called. | |
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) { | |
guard let updatedLocation = locations.last else { return } | |
print("Updated location: \(updatedLocation.coordinate.longitude), \(updatedLocation.coordinate.latitude)") | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment