ios - 应用程序取消并出现 fatal error : unexpectedly found nil while unwrapping an Optional value

标签 ios iphone swift core-location

我正在设计 myCurrentLocationBtn 并在关闭地理定位时在 let center 出现错误

@IBAction func CurrentLocation(sender: AnyObject) {

        let Authflag = CLAuthorizationStatus.self

        print(Authflag)

        let userLocation = locationmanager.location

        let center = CLLocationCoordinate2D(latitude: userLocation!.coordinate.latitude, longitude: userLocation!.coordinate.longitude)

        var currentAnnotation = MKPointAnnotation()
        currentAnnotation.coordinate = center
        currentAnnotation.title = "You're here!"

        MapApple.addAnnotation(currentAnnotation)


}

错误是fatal error: expectedly found nil while unwrapping an Optional value

我该如何解决?

禁用地理定位这样的功能

func locationManager(manager: CLLocationManager, didFailWithError error: NSError) {
        locationmanager.stopUpdatingLocation()
        print (error)
   }

错误此 Error Domain=kCLErrorDomain Code=0 "(null)"

最佳答案

只需使用 guard 来确保它不是 nil:

@IBAction func CurrentLocation(sender: AnyObject) {

    let Authflag = CLAuthorizationStatus.self

    print(Authflag)

    guard let userLocation = locationmanager.location else {
     //tell the user that an error occurred
     return
    }

    let center = CLLocationCoordinate2D(latitude: userLocation.coordinate.latitude, longitude: userLocation.coordinate.longitude)

    var currentAnnotation = MKPointAnnotation()
    currentAnnotation.coordinate = center
    currentAnnotation.title = "You're here!"

    MapApple.addAnnotation(currentAnnotation)


}

关于ios - 应用程序取消并出现 fatal error : unexpectedly found nil while unwrapping an Optional value,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33997568/

相关文章:

iphone - 用于手指手势的移动浏览器模拟器?

ios - 从 iTunes 安装 ipa 文件

iphone - 使用 stringWithContentsOfURL 缓存将 url 内容写入字符串

iOS - float 单按钮

ios - 从 Firebase 获取数据非常慢

ios - UIEventSubtypeRemoteControlTogglePlayPause 什么都不做

ios - 是否可以在屏幕左侧设置 uitabbar?

ios - 异步下载图像时, Collection View 单元格中的图像不会更新

ios - 在 Swift 的 View Controller 中使用 pull_to_refresh

ios - UISearchBarSearchField BackgroundView 颜色