【问题标题】:NSTimer in background mode using locationManager delegate ("Cheat way") SWIFTNSTimer 在后台模式下使用 locationManager 委托(“作弊方式”)SWIFT
【发布时间】:2016-11-23 03:41:25
【问题描述】:

我有一个功能,我想在应用程序后台模式下运行,并且至少每分钟执行一次,以检查 wifi 连接并做出决定。我正在使用 locationManager 委托,所以我可以在后台运行我的 NSTimer。然而,位置管理器消耗了大量的电池电量。此应用程序不适用于 Apple 版本。但是,我正在为位置管理器寻找更有效的设置,这样它就不会那么耗电或任何其他好主意? 我的当前设置还可以,但是由于我为位置管理器启用了自动暂停,因此功能更新延迟太多。在我使用两个委托方法(didEnterRegion 和 didExitRegion)之前,这些方法更耗电且不准确。我阅读了大量可用的教程并检查了有关堆栈溢出的其他相关帖子,但没有找到任何可以帮助我解决问题的内容 这是我的委托函数中的内容:

func locationManager(manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
        self.timer = NSTimer.scheduledTimerWithTimeInterval(45, target: self, selector: #selector(self.checkNetworkSSID), userInfo: nil, repeats: true)
        manager.stopMonitoringSignificantLocationChanges()
        manager.stopUpdatingLocation()
    }

这是我的 viewDidLoadAppDelegate

中的内容
manager = CLLocationManager()
        manager?.delegate = self
        manager?.requestWhenInUseAuthorization()
        manager?.startUpdatingLocation()
        manager?.desiredAccuracy = kCLLocationAccuracyThreeKilometers
        manager?.pausesLocationUpdatesAutomatically = true
        manager?.activityType = CLActivityType.Fitness

【问题讨论】:

    标签: swift location nstimer core-location background-process


    【解决方案1】:

    要在后台获取位置,您需要在您的 代码并确保在 info.plist 中添加 NSLocationAlwaysUsageDescription

            locationManager = CLLocationManager()
            locationManager.delegate = self
            locationManager.desiredAccuracy = kCLLocationAccuracyThreeKilometers
            locationManager.pausesLocationUpdatesAutomatically = false
            locationManager.startMonitoringSignificantLocationChanges()
            if #available(iOS 9.0, *) {
                locationManager.allowsBackgroundLocationUpdates = true
            }
            locationManager.requestAlwaysAuthorization()
            locationManager.startUpdatingLocation()
    

    【讨论】:

    • 我在 plist 中有 NSLocationAlwaysUsageDescription。我真的不关心任何位置变化,因为我不使用它们,我只使用一个委托,所以它可以让我的 NSTimer 保持运行。 startMonitoringSignificantLocationChanges() 究竟是干什么用的呢?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-08-04
    • 1970-01-01
    • 1970-01-01
    • 2011-05-01
    • 1970-01-01
    • 2018-10-11
    • 1970-01-01
    相关资源
    最近更新 更多