我的方法didUpdateLocations似乎从未被调用过?为什么是这样?我已将密钥添加到info.plist
这是我的代码:
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
var locationManager = CLLocationManager()
locationManager.requestWhenInUseAuthorization()
if CLLocationManager.locationServicesEnabled() {
locationManager.delegate = self
locationManager.desiredAccuracy = kCLLocationAccuracyNearestTenMeters
locationManager.startUpdatingLocation()
}
}
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
let locValue:CLLocationCoordinate2D = manager.location!.coordinate
lat = locValue.latitude
long = locValue.longitude
}
答案 0 :(得分:3)
使locationManager
为类变量。您在viewDidLoad
中将其声明为局部变量,这意味着它将被立即释放,因为此函数之外没有强引用。
class YourViewController : UIViewController, CLLocationManagerDelegate
{
var locationManager : CLLocationManager?
override func viewDidLoad()
{
super.viewDidLoad()
locationManager? = CLLocationManager()
locationManager?.requestWhenInUseAuthorization()
if CLLocationManager.locationServicesEnabled()
{
locationManager?.delegate = self
locationManager?.desiredAccuracy = kCLLocationAccuracyNearestTenMeters
locationManager?.startUpdatingLocation()
}
}
}