位置更新不起作用

Location Update not working

即使用户退出视图返回到上一个视图,我也在尝试进行位置更新。 为了实现这一点,我创建了一个单独的 class 来处理我的位置更新,但我遇到了奇怪的行为。

首先,我的授权请求只弹出了一瞬间然后就消失了,所以我将它移回了实际视图。 但是我的位置更新仍然不起作用。 位置图标出现在设备上,但它从未进入 didLocationUpdate 函数。它也没有进入 didFailWithError。 我是 iOS 的新手,所以我不知道我做错了什么。

这是我的 class:

import CoreLocation

class RouteLocation: NSObject, CLLocationManagerDelegate{

    var locationManager:CLLocationManager!

    var databasePath = ""
    override init(){

        super.init()

        let dirPaths =
            NSSearchPathForDirectoriesInDomains(.DocumentDirectory,
                                                .UserDomainMask, true)
        let docsDir = dirPaths[0] as NSString

        databasePath = docsDir.stringByAppendingPathComponent(
            "\firstAscent.db")

        // For use in foreground
        locationManager =  CLLocationManager()
        locationManager.requestWhenInUseAuthorization()


       //   locationManager.requestAlwaysAuthorization()
        //  print("in location")

            if CLLocationManager.locationServicesEnabled() {
                print("System Services enabled")
                self.locationManager.delegate = self
                self.locationManager.desiredAccuracy = kCLLocationAccuracyBest
                self.locationManager.distanceFilter = 10
                self.locationManager.startUpdatingLocation()
            }


    }
    var isLocationMising = true


    func locationManager(manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
        let locValue:CLLocationCoordinate2D = manager.location!.coordinate

        let latitute = locValue.latitude
        let longitute = locValue.longitude
        print("locations = \(locValue.latitude) \(locValue.longitude)") //continues to make SQL query calls 

我从视图中调用它:_ = RouteLocation()

  1. requestWhenInUse... 函数 运行 是异步的。它将显示对话框,但同时继续处理其余代码。即使其他所有内容都是正确的,您的应用也不会在第一次(获得许可时)就正确 运行。
  2. 您是否提供了 requestWhenInUseAuthorization 解释字符串?
  3. 我认为你实例化 class 的方式是 运行 初始化并立即死亡。没有什么可以保留它。 因此无法调用 didUpdateLocation
  4. 如果您只需要一个位置,请致电 requestLocation

您的代码中的一切都很完美,但委托方法不正确

像这样写委托方法

func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {let latitute = locValue.latitude
    let longitute = locValue.longitude
    print("locations = \(locValue.latitude) \(locValue.longitude)")
}