Я практически снял этот код с интернета:
//variables
//location manager
var locationManager:CLLocationManager!
var currentLocation:CLLocation?
//outlets
@IBOutlet weak var whatTextField: UITextField!
@IBOutlet weak var whereTextField: UITextField!
@IBOutlet weak var whenTextField: UITextField!
@IBAction func onCreateEventClick(_ sender: Any) {
let event = CAEvent(eventId: "123777abc", eventName: whatTextField.text, location: currentLocation)
event.save { (error) in
//handle event error
print(error)
}
}
override func viewDidLoad() {
super.viewDidLoad()
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
if( CLLocationManager.authorizationStatus() == .authorizedWhenInUse ||
CLLocationManager.authorizationStatus() == .authorizedAlways){
determineCurrentLocation()
}
}
func determineCurrentLocation() {
locationManager = CLLocationManager()
locationManager.delegate = self
locationManager.desiredAccuracy = kCLLocationAccuracyBest
locationManager.requestWhenInUseAuthorization()
if CLLocationManager.locationServicesEnabled() {
locationManager.startUpdatingLocation()
//locationManager.startUpdatingHeading()
}
}
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
currentLocation = 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 = \(currentLocation?.coordinate.latitude)")
print("user longitude = \(currentLocation?.coordinate.longitude)")
}
func locationManager(_ manager: CLLocationManager, didFailWithError error: Error)
{
print("Error \(error)")
}
И сначала я смог увидеть местоположение (например, не ноль). Теперь, однако, это ноль каждый раз. Я попытался изменить местоположение моего симулятора, и я подтвердил, что приложение в моем симуляторе разделяет местоположение. Я также добавил вызов к startUpdatingLocation()
, добавил делегата didUpdateLocations
и заметил, что didUpdateLocationsAny
не вызывается. Есть еще идеи? Спасибо!