Kha*_*out 2 core-location cllocationmanager ios swift
我正在使用swift4.2并且Xcode 10我正在尝试使iOS应用程序使用位置服务,但它给了我一个例外:Fatal error: Unexpectedly found nil while unwrapping an Optional value
所以我试图检查位置是否返回 nil 所以我复制我的代码并打印位置并返回null,我Xcode从产品>方案>编辑方案>默认位置和调试区域中的检查位置模拟位置,并模拟到位置我选择任何一个知道问题所在吗?
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()
}
}
Run Code Online (Sandbox Code Playgroud)
我已经运行了您的代码,我刚刚在文件中添加了缺少的密钥Privacy - Location When In Use Usage Descriptioninfo.plist。
我对您的代码进行了一些更改并获得了nil价值,因为方法被多次调用,并且当用户授予权限并再次调用方法并打印位置详细信息时,但事实仍然是locationManager可变的,还没有用户位置数据。
在locationManager委托didUpdateLocations调用时获取位置详细信息
我对您的代码进行了一些更改:
import UIKit
import CoreLocation
class ViewController: UIViewController,CLLocationManagerDelegate {
var locationManager = CLLocationManager()
var currentlocation:CLLocation!
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
// authorizelocationstates()
}
func authorizelocationstates(){
if CLLocationManager.authorizationStatus() == .authorizedWhenInUse {
currentlocation = locationManager.location
print(currentlocation)
}
else{
// Note : This function is overlap permission
// locationManager.requestWhenInUseAuthorization()
// authorizelocationstates()
}
}
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
locationManager = manager
// Only called when variable have location data
authorizelocationstates()
}
override func viewDidLoad() {
super.viewDidLoad()
locationManager.delegate = self
locationManager.desiredAccuracy = kCLLocationAccuracyBest
// Get Location Permission one time only
locationManager.requestWhenInUseAuthorization()
// Need to update location and get location data in locationManager object with delegate
locationManager.startUpdatingLocation()
locationManager.startMonitoringSignificantLocationChanges()
}
}
Run Code Online (Sandbox Code Playgroud)
希望它会帮助你。
| 归档时间: |
|
| 查看次数: |
1789 次 |
| 最近记录: |