locationManager.location返回nil
locationManager.location返回nil
我正在使用swift4.2
和Xcode 10
,并且我正在尝试使iOS
应用程序使用位置服务,但是它给了我一个异常:致命错误: 在解包Optional值时意外地发现了nil
\n所以我尝试检查位置是否返回nil,所以我复制了我的代码并打印位置,它返回null
,我在Xcode
中从product>scheme>edit scheme>default location中模拟了位置,并在调试区域中检查了位置,它模拟到我选择的位置。有人知道问题是什么吗? \nimport CoreLocation\nclass LocationVC: UIViewController,CLLocationManagerDelegate {\n let locationManager = CLLocationManager()\n var currentlocation:CLLocation!\n override func viewDidLoad() {\n super.viewDidLoad()\n locationManager.delegate = self\n locationManager.desiredAccuracy = kCLLocationAccuracyBest\n locationManager.requestWhenInUseAuthorization()\n locationManager.startMonitoringSignificantLocationChanges()\n }\n override func viewDidAppear(_ animated: Bool) {\n super.viewDidAppear(animated)\n authorizelocationstates()\n }\n func authorizelocationstates(){\n if CLLocationManager.authorizationStatus() == .authorizedWhenInUse {\n currentlocation = locationManager.location\n print(currentlocation)\n }\n else{\n locationManager.requestWhenInUseAuthorization()\n authorizelocationstates()\n }\n }\n
问题原因:locationManager.location返回nil的原因是因为在调用authorizelocationstates函数获取位置信息时,locationManager变量还没有用户位置数据。
解决方法:修改代码,将获取位置信息的逻辑放在locationManager的代理方法didUpdateLocations中,当代理方法被调用时获取位置信息。
代码修改如下:
import UIKit
import CoreLocation
class ViewController: UIViewController, CLLocationManagerDelegate {
var locationManager = CLLocationManager()
var currentLocation: CLLocation!
override func viewDidLoad() {
super.viewDidLoad()
locationManager.delegate = self
locationManager.desiredAccuracy = kCLLocationAccuracyBest
locationManager.requestWhenInUseAuthorization()
locationManager.startUpdatingLocation()
locationManager.startMonitoringSignificantLocationChanges()
}
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
locationManager = manager
currentLocation = locations.last
print(currentLocation)
}
}
希望对你有所帮助。