locationManager.location returns 无

locationManager.location returns nil

我正在使用 swift4.2Xcode 10,我正在尝试让 iOS 应用程序使用位置服务,但它给了我例外:
Fatal error: Unexpectedly found nil while unwrapping an Optional value

所以我尝试检查位置 returns 是否为 nil 所以我复制我的代码并打印位置和它 returns null ,我从 Xcode 模拟位置=23=]产品>方案>编辑方案>默认位置并检查调试区域中的位置并将其模拟到我选择的位置任何人都知道这个问题吗?

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()
        }
        }

我有 运行 你的代码,我刚刚在 info.plist 文件中添加了缺少的密钥 隐私 - 使用时的位置使用说明

并且我对您的代码进行了一些更改并获得了 nil 值,因为方法被多次调用并且当用户授予权限时再次调用方法并打印位置详细信息但事实仍然是locationManager变量还没有用户位置数据。

当代表 didUpdateLocations 调用

时在 locationManager 中获取位置详细信息

我对你的代码做了一些修改:

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()

    }

}

希望对您有所帮助。