Я работаю над приложением, которое требует получения текущих координат пользователя. Я планировал сделать это с помощью метода CLLocationManager's didUpdateLocations
. По какой-то причине didUpdateLocations
не выполняется. Однако оказывается, что locationManager.startUpdatingLocation()
вызывается успешно. Ни одно из других возможных решений, которые я видел на этом сайте, не работало для меня. Я уже добавил NSLocationAlwaysUsage
в info.plist. Вот полнота моего кода:swift - didUpdateLocations Not Being Called
import UIKit
import MapKit
import CoreLocation
var region: MKCoordinateRegion!
class ViewController: UIViewController, CLLocationManagerDelegate, MKMapViewDelegate {
@IBOutlet weak var map: MKMapView!
var locationManager = CLLocationManager()
override func viewDidLoad() {
super.viewDidLoad()
locationManager.delegate = self
locationManager.desiredAccuracy = kCLLocationAccuracyNearestTenMeters
self.locationManager.requestAlwaysAuthorization()
self.locationManager.requestWhenInUseAuthorization()
switch CLLocationManager.authorizationStatus() {
case .authorizedWhenInUse, .authorizedAlways:
if CLLocationManager.locationServicesEnabled() {
locationManager.startUpdatingLocation()
print("Updating location now")
}
case .notDetermined:
locationManager.requestAlwaysAuthorization()
case .restricted, .denied:
print("User must enable access in settings")
break
}
if (region == nil){
}
else {
map.setRegion(region!, animated: true)
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
}
func locationManager(manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
print("Got location")
let userLocation:CLLocation = locations[0]
let lat:CLLocationDegrees = userLocation.coordinate.latitude
let long:CLLocationDegrees = userLocation.coordinate.longitude
let currentPos:CLLocationCoordinate2D = CLLocationCoordinate2DMake(lat, long)
didUpdateRegion(position: currentPos)
print(lat)
print(long)
}
func didUpdateRegion(position: CLLocationCoordinate2D) {
let span = MKCoordinateSpanMake(0.075, 0.075)
region = MKCoordinateRegion(center: position, span: span)
}
func locationManager(_manager: CLLocationManager, didFailWithError error: Error) {
print(error.localizedDescription)
}
func locationManager(manager: CLLocationManager!, didChangeAuthorizationStatus status: CLAuthorizationStatus) {
switch status {
case .notDetermined:
// If status has not yet been determied, ask for authorization
manager.requestWhenInUseAuthorization()
break
case .authorizedWhenInUse:
// If authorized when in use
manager.startUpdatingLocation()
break
case .authorizedAlways:
// If always authorized
manager.startUpdatingLocation()
break
case .restricted:
print("User must activate location services in settings")
break
case .denied:
print("User must activate location services in settings")
break
default:
break
}
}
Когда я запускаю этот код как на тренажере и фактическое устройство, я получаю уведомление, чтобы разрешить отслеживание местоположения. Приняв это, консоль отобразит «Обновление местоположения сейчас», но никогда не печатает «Got location». Спасибо за любой свет, который вы можете пролить на эту проблему, я новичок в разработке приложений в целом.
EDIT: Я добавил полностью код, а не только те части, которые, как я думал, были релевантными. В основном, я пытаюсь заставить регион, показанный на карте, следовать за пользователем. Я пытаюсь сделать это, обновляя переменную «область» каждый раз, когда срабатывает функция didUpdateLocations
.
Проверить locationServicesEnabled установлено значение true – Gruntcakes
Да, locationServicesEnabled был установлен в true. –
Возможно, неплохо было бы опубликовать весь код, а не фрагменты. – Gruntcakes