【发布时间】:2019-06-20 17:26:12
【问题描述】:
我正在使用swift4.2 和Xcode 10,我正在尝试使iOS 应用程序使用定位服务,但它给了我例外:Fatal error: Unexpectedly found nil while unwrapping an Optional value
所以我尝试检查 location 是否返回 nil 所以我复制我的代码并打印位置并返回 null ,我从 product>scheme 模拟了 Xcode 中的位置strong>>编辑方案>默认位置并检查调试区域中的位置,它模拟到我选择的位置有人知道问题吗?
import CoreLocation
class LocationVC: UIViewController,CLLocationManagerDelegate {
let locationManager = CLLocationManager()
var currentlocation:CLLocation!
override func viewDidLoad() {
super.viewDidLoad()
locationManager.delegate = self
locationManager.desiredAccuracy = kCLLocationAccuracyBest
locationManager.requestWhenInUseAuthorization()
locationManager.startMonitoringSignificantLocationChanges()
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
authorizelocationstates()
}
func authorizelocationstates(){
if CLLocationManager.authorizationStatus() == .authorizedWhenInUse {
currentlocation = locationManager.location
print(currentlocation)
}
else{
locationManager.requestWhenInUseAuthorization()
authorizelocationstates()
}
}
【问题讨论】:
-
确保将其添加到 plist 中
-
您必须实现适当的委托方法,例如locationManager(_:didUpdateLocations:)
-
如果用户没有授权使用位置信息,您的
authorizelocationstates可能会进入无限循环。请找到一些关于使用核心位置的好教程。
标签: ios swift core-location cllocationmanager