Ale*_*ser 0 cllocation ios swift
I have essentially lifted this code from the internet:
//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)")
}
Run Code Online (Sandbox Code Playgroud)
And at first I was able to see the location (e.g., not nil.). Now however, it is nil every single time. I have tried changing my simulator's location, and I have confirmed that the app in my simulator is sharing location. I also have added a call to startUpdatingLocation() and added the delegate didUpdateLocations and noticed that didUpdateLocationsAny is not called. Any other ideas? Thanks!
小智 5
你调用locationManager的方法startUpdatingLocation()吗?开始更新位置的最佳位置是 locationManager 的委托方法:
func locationManager(_ manager: CLLocationManager, didChangeAuthorization status: CLAuthorizationStatus) {
switch(CLLocationManager.authorizationStatus()) {
case .authorizedAlways, .authorizedWhenInUse:
locationManager.startUpdatingLocation()
case .denied, .notDetermined, .restricted:
locationManager.stopUpdatingLocation()
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2210 次 |
| 最近记录: |