我想制作一个简单的 iOS 应用程序,使用位置数据。不幸的是,在设备和模拟器上进行测试时,即使我在模拟器上输入“当前位置”调试代码,我也会收到“nil”。 这是我第一次在 swift 3 上使用 CoreLocation,所以我使用了与之前相同的方法。
import UIKit
import CoreLocation
class ViewController: UIViewController, CLLocationManagerDelegate {
@IBOutlet weak var latitudeLabel: UILabel!
@IBOutlet weak var longitudeLabel: UILabel!
var locationManager:CLLocationManager?
var currentLocation:CLLocation?
override func viewDidLoad() {
super.viewDidLoad()
let locationManager = CLLocationManager()
locationManager.delegate = self
locationManager.desiredAccuracy = kCLLocationAccuracyBest
locationManager.requestAlwaysAuthorization()
locationManager.startUpdatingLocation()
updateLabels()
// Do any additional setup after loading the view, typically from a nib.
}
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
self.currentLocation = locations[0]
}
func locationManager(_ manager: CLLocationManager, didFailWithError error: Error) {
print(error)
}
func updateLabels() {
latitudeLabel.text = String(describing: currentLocation?.coordinate.latitude)
longitudeLabel.text = String(describing: currentLocation?.coordinate.longitude)
print(currentLocation)
}
}
当然,我已经在 Info.plist 中编写了所有必要的隐私 key 。
当我尝试打印 currentLocation 时,我收到了 nil。 在上次启动时我发现了这样的问题,比起出现警报,但立即消失
最佳答案
在 viewDidLoad
中,您将 CLLocationManager
保存在局部变量中,但从未将其保存到您的属性中。因此,它超出范围并被释放,可能永远不会调用您的委托(delegate)方法。
要么直接更新您的属性,要么在您配置完位置管理器后,确保执行 self.locationManager = locationManager
。我可能会直接更新它:
override func viewDidLoad() {
super.viewDidLoad()
locationManager = CLLocationManager()
locationManager?.delegate = self
locationManager?.desiredAccuracy = kCLLocationAccuracyBest
locationManager?.requestAlwaysAuthorization()
locationManager?.startUpdatingLocation()
// updateLabels()
}
然后,正如 rmaddy 指出的那样,在 didUpdateLocations
中更新您的标签:
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
guard let location = locations.last, location.horizontalAccuracy >= 0 else { return }
currentLocation = location
updateLabels()
}
关于ios - 位置问题 swift 3,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40985512/