didUpdateLocations 方法未被调用
didUpdateLocations method not being called
我的方法 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
}
使 locationManager
成为 class 变量。您在 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()
}
}
}
我的方法 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
}
使 locationManager
成为 class 变量。您在 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()
}
}
}