Ios 位置问题swift 3
我想使用位置数据制作一个简单的iOS应用程序。不幸的是,在设备和模拟器上进行测试时,即使在模拟器上输入“当前位置”调试代码,我也会收到“nil”。 这是我第一次在swift 3上使用CoreLocation,所以我使用了与以前相同的方法Ios 位置问题swift 3,ios,swift,swift3,core-location,Ios,Swift,Swift3,Core Location,我想使用位置数据制作一个简单的iOS应用程序。不幸的是,在设备和模拟器上进行测试时,即使在模拟器上输入“当前位置”调试代码,我也会收到“nil”。 这是我第一次在swift 3上使用CoreLocation,所以我使用了与以前相同的方法 import UIKit import CoreLocation class ViewController: UIViewController, CLLocationManagerDelegate { @IBOutlet weak var latit
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中编写了所有必要的隐私密钥
当我试图打印currentLocation时,我收到零。
在上次发布时,我发现了这样的问题,随后出现了一个警报,但立即消失了,因为您从错误的位置调用了
updateLabels
。您需要从locationManager(\uuquo:didUpdateLocations)
方法内部调用它。由于委托方法可能在后台线程上调用,请确保使用DispatchQueue.main.async
在viewDidLoad
中包装对updateLabels
的调用,但决不将其保存到属性中。因此,它超出了范围并被释放,可能永远不会调用您的委托方法
直接更新您的属性,或者在配置完位置管理器后,确保执行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()
}
你说“我收到‘零’是什么意思?请澄清您的问题。感谢您的回复。编辑说明。