仅在模拟器 iPhone6 - XCode 9.4.1 中首次启动时出现位置权限问题

Problem with location permission during first time launch only in simulator iPhone6 - XCode 9.4.1

我有一个奇怪的问题。 该问题仅在 iPhone6 模拟器中出现。 当我第一次启动应用程序时,未经许可,然后在此代码中显示失败。此代码位于 ViewDidLoad in main ViewController

manager.delegate = self
manager.requestWhenInUseAuthorization()
manager.desiredAccuracy = kCLLocationAccuracyBest
manager.startUpdatingLocation()
var curLoc:CLLocation!
curLoc = manager.location
mapView.delegate = self
if (isLocationPermissionGranted() == false){
         MapView.setRegion(MKCoordinateRegion(center: CLLocationCoordinate2D(latitude: 52.406464, longitude: 16.924997), span: MKCoordinateSpan(latitudeDelta: 0.1, longitudeDelta: 0.1)), animated: true)
        }else
        {
         MapView.setRegion(MKCoordinateRegionMake(CLLocationCoordinate2DMake(curLoc.coordinate.latitude, curLoc.coordinate.longitude), MKCoordinateSpan(latitudeDelta: 0.1, longitudeDelta: 0.1)), animated: true)
        }

        let getJSON = JSONDownload()
        getJSON.JSONDownloader(MapView: MapView)
    }

在 else 块中我有错误

Thread 1: Fatal error: Unexpectedly found nil while unwrapping an Optional value

但在任何其他模拟器或我的 phone(iPhone 6s, iOS 11.4.1) 中只显示

Could not inset legal attribution from corner 4

关于这条消息,我也有点困惑,因为我想,我拥有所有权限选项。

我的许可内容是:

在Info.plist

Privacy - Location When In Use Usage Description

Privacy - Location Usage Description

在代码中 ViewController

let manager = CLLocationManager()

另外,我有针对本地化错误的保护:

func isLocationPermissionGranted() -> Bool{
guard CLLocationManager.locationServicesEnabled() else{
    return false
}
return [.authorizedAlways, .authorizedWhenInUse].contains(CLLocationManager.authorizationStatus())
}

有机会修复吗? :) 谢谢解答! :)

在您的代码中,您将 curLoc 声明为隐式展开的可选值,然后将 manager.location 分配给它;但是 manager.location 是可选的,可能是 nillocation 可能是 nil 的原因有很多;设备确定其位置需要时间,或者用户可能拒绝了位置访问。

无论什么原因,当你随后访问 curLoc 时它包含 nil 你会得到一个异常,因为隐式解包可选的合同是它不会 nil .

您需要安全地打开 manager.location 以避免崩溃。

mapView.delegate = self

if let curLoc = manager.location, isLocationPermissionGranted() {         
    MapView.setRegion(MKCoordinateRegionMake(CLLocationCoordinate2DMake(curLoc.coordinate.latitude, curLoc.coordinate.longitude), MKCoordinateSpan(latitudeDelta: 0.1, longitudeDelta: 0.1)), animated: true)
} else {
    MapView.setRegion(MKCoordinateRegion(center: CLLocationCoordinate2D(latitude: 52.406464, longitude: 16.924997), span: MKCoordinateSpan(latitudeDelta: 0.1, longitudeDelta: 0.1)), animated: true)
}