![](/img/trans.png)
[英]iOS - CLLocation Manager didUpdateLocations called too much time
[英]iOS - CLLocation Manager didUpdateLocations being called in one class but not another?
嗨,我正在制作一个程序,该程序可以获取用户的位置并将相应的注释放在地图上。 我从在View Controller中编写所有代码开始,它可以完美地获得位置。 以下是视图控制器中的工作代码。
class MapViewController: UIViewController, CLLocationManagerDelegate {
var annotation = MKPointAnnotation()
var userLocation: CLLocation?
@IBOutlet weak var mapView: MKMapView!
var locationManager:CLLocationManager!
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
determineCurrentLocation()
}
func determineCurrentLocation() {
locationManager = CLLocationManager()
locationManager.delegate = self
locationManager.desiredAccuracy = kCLLocationAccuracyBest
locationManager.requestAlwaysAuthorization()
if CLLocationManager.locationServicesEnabled() {
locationManager.startUpdatingLocation()
}
}
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
userLocation = locations[0] as CLLocation
print("user latitude = \(userLocation?.coordinate.latitude)")
print("user longitude = \(userLocation?.coordinate.longitude)")
annotation.coordinate = CLLocationCoordinate2D(latitude: (userLocation?.coordinate.latitude)!, longitude: (userLocation?.coordinate.longitude)!)
annotation.title = "You"
mapView.addAnnotation(annotation)
}
func locationManager(_ manager: CLLocationManager, didFailWithError error: Error) {
print("Error \(error)")
}
但是现在当我尝试在另一个swift文件中重新创建几乎完全相同的代码时。 didUpdateLocations永远不会被调用。 locationManager.startUpdatingLocation()确实被调用。
以下是我从View Controller调用的新的swift文件。 我是否在这里缺少任何简单的概念,因为我真的不明白为什么这不起作用。
import Foundation
import CoreLocation
class SendLocation: NSObject, CLLocationManagerDelegate {
var userLocation: CLLocation?
var locationManager:CLLocationManager!
func sendLocationPost() {
determineCurrentLocation()
}
func determineCurrentLocation() {
locationManager = CLLocationManager()
locationManager.delegate = self
locationManager.desiredAccuracy = kCLLocationAccuracyBest
locationManager.requestAlwaysAuthorization()
print("WHY")
if CLLocationManager.locationServicesEnabled(){
locationManager.startUpdatingLocation()
}
}
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
userLocation = locations[0] as CLLocation
print("user latitude = \(userLocation?.coordinate.latitude)")
print("user longitude = \(userLocation?.coordinate.longitude)")
}
func locationManager(_ manager: CLLocationManager, didFailWithError error: Error) {
print("Error \(error)")
}
}
我称它为:
let location = SendLocation()
location.sendLocationPost()`
在我的View Controller中
发生这种情况是因为您没有保留对SendLocation对象的引用。
将SendLocation设置为UIViewController的属性。
例如,从静态作用域调用它不会保留引用。
工作:
static func sendLocation() {
let location = SendLocation()
location.sendLocationPost()
}
将工作
let location = SendLocation()
func sendLocation() {
location.sendLocationPost()
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.