我有一个问题,因为当我尝试获取位置用户并在我的 .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/