I want to know the user's current location. But since I want to get this location from multiple places, I made a function for it instead of setting a particular UIViewController
as delegate handler.
Methods to get user location:
func getUserLocation(completion: @escaping (String?) -> Void) {
let locationManager = CLLocationManager()
let geoCoder = CLGeocoder()
let authorizationStatus = CLLocationManager.authorizationStatus()
print("Authorization status: ", authorizationStatus.rawValue, " ," , CLAuthorizationStatus.notDetermined.rawValue)
if authorizationStatus == CLAuthorizationStatus.notDetermined {
print("Asking for location authorization")
locationManager.requestWhenInUseAuthorization()
}
if authorizationStatus == CLAuthorizationStatus.denied {
completion(nil)
}
if authorizationStatus == CLAuthorizationStatus.authorizedWhenInUse || authorizationStatus == CLAuthorizationStatus.authorizedAlways {
if CLLocationManager.locationServicesEnabled() {
guard let currentLocation = locationManager.location else { return completion(nil) }
geoCoder.reverseGeocodeLocation(currentLocation) { (placemarks, error) in
guard let currentLocPlacemark = placemarks?.first else { return completion(nil) }
print(currentLocPlacemark.country ?? "No country found")
print(currentLocPlacemark.isoCountryCode ?? "No country code found")
guard let isoCode = currentLocPlacemark.isoCountryCode else { return completion(nil) }
completion(isoCode)
}
}
}
}
func incrementLocationInFirebase() {
getUserLocation { (location) in
if let location = location {
//Save Location to Firebase
print("Location: ", location)
}
}
}
func decrementLocationInFirebase() {
// Fetch saved location
// Decrement from firebase
}
I have set 2 description string:
- Privacy - Location Usage Description
- Privacy - Location When In Use Usage Description
I call incrementLocationInFirebase()
from my main view controller from viewDidAppear
. The location request pops up briefly on the simulator before disappearing. But the popup is not interactable when it is briefly visible. And it never shows up on the actual device.
Output on simulator:
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…