繁体   English   中英

didUpdateLocations没有被称为swift 3

[英]didUpdateLocations not getting called swift 3

我正在开发一个屏幕,该屏幕需要使用计时器每10分钟更新一次位置。 除此之外,它仅需要在第一次加载时以及在视图再次显示给用户时更新位置。 一旦用户转到另一个视图,它应该停止监视。

我有一个应该执行此操作的代码,但问题是在任何时候都不会调用didUpdateLocations方法。 此外,地图未显示当前位置(我使用模拟位置)。

我已经正确设置了权限,并且将其设置为仅显示位置时,该应用程序运行正常。 我需要这样做以减少电池消耗。

这是我的相关代码:

viewDidLoad

if #available(iOS 8.0, *) {
            self.locationManager.requestAlwaysAuthorization()
        }
        self.locationManager.allowsBackgroundLocationUpdates = true
        self.locationManager.distanceFilter = 1000
        self.locationManager.activityType = CLActivityType.automotiveNavigation
        self.locationManager.desiredAccuracy = kCLLocationAccuracyBest
        self.locationManager.pausesLocationUpdatesAutomatically = false
        self.locationManager.startUpdatingLocation()
self.map.showsUserLocation = true

viewWillAppear

self.map.showsUserLocation = true
        self.locationManager.startUpdatingLocation()

viewWillDisappear

self.map.showsUserLocation = false
            self.locationManager.stopUpdatingLocation()

didUpdateLocations :(在最后一行)

self.locationManager.stopUpdatingLocation()

计时器功能:(这很好)

Timer.scheduledTimer(timeInterval: 600.0, target: self, selector: #selector(HomePageViewController.updateLocationFromTimer), userInfo: nil, repeats: true)

   @objc func updateLocationFromTimer()
    {
        self.locationManager.startUpdatingLocation()
    }

我还尝试使用以下代码捕获任何错误:

func locationManager(_ manager: CLLocationManager, didFailWithError error: Error) {
        print(error.localizedDescription)
    }

但没有被调用。

我想知道为什么未更新位置以及地图未显示位置。 请帮忙。

确保分配了委托:

self.locationManager.delegate = self

我也没有为我工作,而是发现您设置代表的位置对此有影响。

例如,这不起作用:

  var locationManager = CLLocationManager() {
        didSet {
            locationManager.delegate = self
        }
    }

稍后将其设置为预期的效果。 不知道为什么要诚实,但这也许可以帮助某人。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM