gpt4 book ai didi

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

转载 作者:搜寻专家 更新时间:2023-10-31 22:08:27 24 4
gpt4 key购买 nike

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

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com