第一:抱歉标题不好。我不知道如何更好地描述我的问题。
我的 Xcode 项目中有这个代码:
import UIKit
import CoreLocation
class ViewController: UIViewController, CLLocationManagerDelegate {
let locationManager = CLLocationManager()
var currentLocation = "PLACEHOLDER"
override func viewDidLoad() {
self.locationManager.requestWhenInUseAuthorization()
locationManager.delegate = self
locationManager.desiredAccuracy = kCLLocationAccuracyNearestTenMeters
super.viewDidLoad()
}
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
guard let locValue: CLLocationCoordinate2D = manager.location?.coordinate else { return }
currentLocation = String(locValue.latitude)
}
@IBAction func sendLocation() {
locationManager.startUpdatingLocation()
print(currentLocation)
locationManager.stopUpdatingLocation()
}
}
这会在单击 UIButton 时打印用户位置。
这是有效的。但是由于某种原因,在重新启动应用程序后第一次按下 UIButton 时,它会打印PLACEHOLDER
而不是位置。
意味着:当我启动应用程序并单击 UIButton 三次时,我在控制台中得到了这个:
PLACEHOLDER
56.153666216328625
56.153666216328625
而不是这个:
56.153666216328625
56.153666216328625
56.153666216328625
我也尝试存储 asUserDefaults
而不是 as var
,但这会导致同样的问题。
我究竟做错了什么?