我有以下Location
类,我想返回当前位置。但是,我无法获得当前位置。我相信我已经添加了所有正确的PLIST项目并添加了Core Location框架。当我点按getLocation
时,权限消失,我无法批准。
调试器返回以下内容:
CLLocationManager.locationServicesEnabled() true
location Services Enabled
locationManager.delegate <Shot_On_Goal.Location: 0x1c001f560>
@IBAction func getLocation(_ sender: Any) {
let location = Location()
location.getCurrentLocation()
}
import Foundation
import MapKit
import CoreLocation
class Location: NSObject {
var locationManager: CLLocationManager!
func getCurrentLocation() {
print("class->Location->getCurrentLocation")
locationManager = CLLocationManager()
if (CLLocationManager.locationServicesEnabled())
{
print("location Services Enabled")
locationManager.delegate = self
locationManager.desiredAccuracy = kCLLocationAccuracyNearestTenMeters
locationManager.requestWhenInUseAuthorization()
locationManager.startUpdatingLocation()
} else {
locationManager.stopUpdatingLocation()
}
}
} // class
extension Location: CLLocationManagerDelegate {
func locationManager(_ manager: CLLocationManager, didFailWithError error: Error) {
print("class->Location->didFailWithError")
print("Error to update location \(error)")
}
func locationManager(_ manager: CLLocationManager, didChangeAuthorization status: CLAuthorizationStatus) {
print("class->Location->didChangeAuthorization")
switch status {
case .notDetermined:
print("notDetermined")
case .restricted:
print("restricted")
case .denied:
print("denied")
case .authorizedAlways:
print("authorizedAlways")
case .authorizedWhenInUse:
print("authorizedWhenInUse")
}
}
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
print("class->Location->didUpdateLocations")
let locValue:CLLocationCoordinate2D = manager.location!.coordinate
print("locations = \(locValue.latitude) \(locValue.longitude)")
}
} //extension
答案 0 :(得分:2)
问题是这段代码:
let location = Location() // <-- oops
location.getCurrentLocation()
此Location实例需要是持久保留对象(例如某些持久视图控制器或app delegate的全局或实例属性)。它可以不是你所拥有的局部变量;它在它可以做任何工作之前就消失了。