我正在尝试在我的应用程序中使用位置管理器。我设置了我在很多帖子和示例中看到的代码,一切正常,我让位置管理器显示模拟器中设置的当前位置。然后我在模拟器中更改位置,我的应用程序获取新位置。
然后我重新启动我的计算机,然后重新启动我的应用程序,但位置管理器停止工作。我尝试使用addObserver()更改代码以使用didUpdateLocations,有时我设法重新启动位置管理器才能工作。但是当我重新启动机器时它再次停止工作。我尝试重置模拟器并再次授权应用程序获取位置更新,但没有成功。在所有情况下,我的应用程序打印出它有权获取位置更新,但它不起作用。我也尝试清理应用程序并重建它,但没有成功。 以下是我使用的代码的两个版本。
使用addObserver的代码
class TViewController: UIViewController, GMSMapViewDelegate, CLLocationManagerDelegate {
var myLocation: CLLocation?
var locationManager = CLLocationManager()
@IBOutlet weak var mapView: GMSMapView!
override func viewDidLoad() {
super.viewDidLoad()
locationManager.desiredAccuracy = kCLLocationAccuracyBest;
locationManager.distanceFilter = kCLDistanceFilterNone;
locationManager.delegate = self
locationManager.requestWhenInUseAuthorization()
mapView!.settings.myLocationButton = true
}
// get updates of myLocation
override func observeValueForKeyPath(keyPath: String?,
ofObject object: AnyObject?,
change: [String : AnyObject]?,
context: UnsafeMutablePointer<Void>)
{
myLocation = change![NSKeyValueChangeNewKey] as? CLLocation
print("in newlocation = \(myLocation)")
}
func locationManager(manager: CLLocationManager, didChangeAuthorizationStatus status: CLAuthorizationStatus) {
if status == CLAuthorizationStatus.AuthorizedWhenInUse {
print("in myLocation is authorized")
locationManager.startUpdatingLocation()
mapView!.myLocationEnabled = true
mapView!.addObserver(self, forKeyPath: "myLocation", options: NSKeyValueObservingOptions.New, context: nil)
}
}
}
使用didUpdateLocations的代码
extension TViewController: CLLocationManagerDelegate {
func locationManager(manager: CLLocationManager, didChangeAuthorizationStatus status: CLAuthorizationStatus) {
if status == .AuthorizedWhenInUse {
print("in myLocation extension is authorized")
isLocationAvailable = true
locationManager.startUpdatingLocation()
mapView.myLocationEnabled = true
mapView.settings.myLocationButton = true
}
}
func locationManager(manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
myLocation = locations.first
print("in newlocation extension = \(myLocation)")
mapView.camera = GMSCameraPosition(target: myLocation!.coordinate, zoom: 15, bearing: 0, viewingAngle: 0)
}
class TViewController: UIViewController, GMSMapViewDelegate {
var myLocation: CLLocation?
var locationManager = CLLocationManager()
@IBOutlet weak var mapView: GMSMapView!
override func viewDidLoad() {
super.viewDidLoad()
locationManager.desiredAccuracy = kCLLocationAccuracyBest;
locationManager.distanceFilter = kCLDistanceFilterNone;
locationManager.delegate = self
locationManager.requestWhenInUseAuthorization()
mapView!.settings.myLocationButton = true
}