我尝试获取latitude
和longitude
但位置始终为nil
。
class FinalizeOrderController: UIViewController {
var locManager = CLLocationManager()
var currentLocation: CLLocation!
override func viewDidLoad() {
super.viewDidLoad()
currentLocation = CLLocation()
locManager.requestWhenInUseAuthorization()
// Do any additional setup after loading the view.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@IBAction func FinaliseOrder(_ sender: Any) {
if (CLLocationManager.authorizationStatus() == CLAuthorizationStatus.authorizedWhenInUse ||
CLLocationManager.authorizationStatus() == CLAuthorizationStatus.authorizedAlways) {
currentLocation = locManager.location
print(locManager.location?.coordinate.latitude) //prints nil
print(currentLocation.coordinate.longitude) //fatal error: unexpectedly found nil while unwrapping an Optional value
}
lbl1.text = "\(currentLocation.coordinate.longitude)"
lbl2.text = "\(currentLocation.coordinate.latitude)"
}
我添加 info.plist 键并从Xcode
运行模拟器位置,并从调试中选择模拟器位置,但始终不能nil
答案 0 :(得分:2)
试试这个:
var locationManager: CLLocationManager?
var currentLocation:CLLocation?
遵守代表
class ViewController: UIViewController,CLLocationManagerDelegate
在ViewDidLoad
中 override func viewDidLoad() {
super.viewDidLoad()
locationManager = CLLocationManager();
locationManager.delegate = self;
locationManager.desiredAccuracy = kCLLocationAccuracyBest
let authorizationStatus = CLLocationManager.authorizationStatus()
if (authorizationStatus == CLAuthorizationStatus.NotDetermined) {
locationManager.requestWhenInUseAuthorization()
} else {
locationManager.startUpdatingLocation()
}
}
代表
func locationManager(manager: CLLocationManager!, didUpdateLocations locations: [AnyObject]!) {
currentLocation = locations[locations.count-1] as CLLocation
print("locations = \(currentLocation)")
// lbl1.text = "\(currentLocation.coordinate.latitude)";
// lbl2.text = "\(currentLocation.coordinate.longitude)";
}
按钮操作
@IBAction func FinaliseOrder(_ sender: Any) {
lbl1.text = "\(currentLocation.coordinate.longitude)"
lbl2.text = "\(currentLocation.coordinate.latitude)"
}