ios - CLLocationManager fatal error : unexpectedly found nil while unwrapping an Optional value Swift

标签 ios swift mkmapview cllocationmanager

我有一个问题,因为当我尝试获取位置用户并在我的 .plist 中获得权限时,我的应用程序崩溃了,这是我的代码。

import UIKit
import MapKit
import CoreLocation

class mapClass : UIViewController,MKMapViewDelegate,CLLocationManagerDelegate{

    var location4 = CLLocation()
    var lm  = CLLocationManager ()

    @IBOutlet  var propMapa: MKMapView!

    lm.delegate=self
    lm.desiredAccuracy = kCLLocationAccuracyNearestTenMeters
    lm.distanceFilter = kCLDistanceFilterNone
    lm.startUpdatingLocation()

    println("\(lm.location)") <---- nil

   location4 = lm.location <---- crash

}

日志: fatal error :在展开可选值时意外发现 nil

最佳答案

调用 lm.startUpdatingLocation() 后,位置管理器会在检测到位置更改时调用 didUpdateLocations(),因此您需要实现 CLLocationManager::didUpdateLocations 检索位置:

import UIKit
import MapKit
import CoreLocation

class mapClass : UIViewController,MKMapViewDelegate,CLLocationManagerDelegate{

    var location4 = CLLocation()
    var lm  = CLLocationManager ()

    @IBOutlet  var propMapa: MKMapView!

    ...

    lm.delegate=self
    lm.desiredAccuracy = kCLLocationAccuracyNearestTenMeters
    lm.distanceFilter = kCLDistanceFilterNone
    lm.startUpdatingLocation()
}

func locationManager(manager: CLLocationManager!, didUpdateLocations locations: [AnyObject]!) {

    let currentLocation = locations.last as CLLocation
    println(currentLocation)
    ...
}

关于ios - CLLocationManager fatal error : unexpectedly found nil while unwrapping an Optional value Swift,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29058088/

相关文章:

iphone - 如何开始复杂级别的跨平台移动应用程序开发?

swift - Xcode 8 测试版 6 : AnyObject replaced by Any: where is classForCoder?

ios - 在 "Charts by Daniel Cohen Gindi"的图表绘制自身之后,屏幕上的 UIButton 不再可选

iPhone MKMapView : Detecting Nearest Locations in Array from Current Location

iphone - iPhone 二维码阅读器

objective-c - ios_type ^=0x1,这是什么意思?

ios - 您应该为 UIAccessibilityConvertFrameToScreenCoordinates 使用哪个 View ?

ios - 如何将度数转换为弧度?

iphone - 防止 MKMapView 不断重新缩放并重新居中到用户位置

macos - 在 XCode 中寻找 MKMapView 缩放按钮