Ios 线程1:致命错误:使用CoreLocation隐式展开可选值时意外发现nil

Ios 线程1:致命错误:使用CoreLocation隐式展开可选值时意外发现nil,ios,swift,xcode,core-location,cllocationmanager,Ios,Swift,Xcode,Core Location,Cllocationmanager,我对swift真的很陌生,我正试图弄明白为什么我在运行这个程序时会得到一个零值。我曾尝试添加一个func locationManager(manager:CLLocationManager!、didUpdateLocations locations:[CLLocation]!),但这似乎不起作用。任何帮助都将不胜感激。谢谢 下面是代码(PS:这是变量locManager的值:var locManager=CLLocationManager() override func viewDidLoad(

我对swift真的很陌生,我正试图弄明白为什么我在运行这个程序时会得到一个零值。我曾尝试添加一个
func locationManager(manager:CLLocationManager!、didUpdateLocations locations:[CLLocation]!)
,但这似乎不起作用。任何帮助都将不胜感激。谢谢

下面是代码(PS:这是变量locManager的值:
var locManager=CLLocationManager()

override func viewDidLoad(){
super.viewDidLoad()
tableView.backgroundColor=UIColor.systemGreen
tableView.estimatedRowHeight=100
tableView.rowHeight=UITableView.automaticDimension
locManager.RequestWhenUseAuthorization()
func locationManager(管理器:CLLocationManager!,didUpdateLocations位置:[CLLocation]!){
让locationZoom=locations.last为!CLLocation
}
如果CLLocationManager.authorizationStatus()=.authorizedWhenInUse | | CLLocationManager.authorizationStatus()=.AuthorizationDalWays
{
currentLocation=locManager.location
//获取位置

设longa=currentLocation.coordinate.longitude***可能currentLocation=nil。使用

if let currentLocation = locManager.location {
    // Code for currentLocation != nil
} else {
    // Code for currentLocation == nil
}

或者类似的东西。

有两个主要问题:

  • 方法
    didUpdateLocations
    必须在类的顶层声明(与
    viewDidLoad
    的级别相同),并且处理位置的所有代码必须在此方法内

    func locationManager(manager: CLLocationManager!, didUpdateLocations locations: [CLLocation]!) {
         guard let currentLocation = locations.last else { return }
         //getting locations
         let longa = currentLocation.coordinate.longitude 
         let latta = currentLocation.coordinate.latitude
         nearbyLocations1(latitude: latta, longitude: longa) { (longitude, latitude, name, vicinity) in                       
             print("name 1 is ", name)
         }
         nearbyLocations2(latitude: latta, longitude: longa) { (longitude, latitude, name, vicinity) in
             print("name 2 is ", name)
         }
    }
    
  • 要获取位置,您必须将位置管理器的委托设置为
    self
    并调用
    startUpdatingLocation()

  • 这似乎不起作用。程序没有显示错误,但代码没有被执行
    func locationManager(manager: CLLocationManager!, didUpdateLocations locations: [CLLocation]!) {
         guard let currentLocation = locations.last else { return }
         //getting locations
         let longa = currentLocation.coordinate.longitude 
         let latta = currentLocation.coordinate.latitude
         nearbyLocations1(latitude: latta, longitude: longa) { (longitude, latitude, name, vicinity) in                       
             print("name 1 is ", name)
         }
         nearbyLocations2(latitude: latta, longitude: longa) { (longitude, latitude, name, vicinity) in
             print("name 2 is ", name)
         }
    }