无法在后台使用应用程序保持GPS处于活动状态,或者在前台或后台使用应用程序无法读取位置

塞缪尔·海登(Samuel Hayden)

与该问题相关的应用旨在即使用户按下了睡眠按钮,也可以在30分钟的时间内以高精度跟踪用户位置,包括GPS坐标和加速度计读数。

为此,plist文件和应用程序功能设置已更改,以反映始终启用导航访问的原因并启用后台进程以提供基于位置的服务。

该应用程序确实会在运行时向用户询问GPS权限,如果被授予,则激活此视图控制器(包含以下代码的视图控制器)的确会导致GPS /导航图标显示在iPhone上。

问题是,到目前为止,下面看到的四个“打印”命令中没有一个导致任何打印的消息,因此“ newLocation”和“ myLocation”变量都不会产生任何数据。如果此代码几乎无法满足第一句中概述的目的,那么问题是“如何解决?”。如果这是实现目标的不好方法,那么更好的答案将解释该如何完成。

import UIKit
import CoreMotion
import MapKit
import CoreLocation

class ActiveSession: UIViewController, CLLocationManagerDelegate {
        lazy var locationManager: CLLocationManager! = {
        let manager = CLLocationManager()
        manager.desiredAccuracy = kCLLocationAccuracyBest
        manager.delegate = self
        return manager
    }()

    func locationManager(_manager: CLLocationManager!, didUpdateToLocation newLocation: CLLocation!, fromLocation oldLocation: CLLocation!) {
        let myLocation:CLLocationCoordinate2D=CLLocationCoordinate2DMake(oldLocation.coordinate.latitude, oldLocation.coordinate.longitude)
        print(myLocation)

        if UIApplication.shared.applicationState == .active {
            print("at least it's active at all")
        } else {
            print(newLocation)
            print("it's active when the app isn't")
        }
    }

     func getPermission () {
        locationManager = CLLocationManager()

        switch CLLocationManager.authorizationStatus() {
        case .denied, .restricted:
            return
        case .notDetermined:
            locationManager!.requestAlwaysAuthorization()
            break
        case .authorizedAlways, .authorizedWhenInUse:
            break
        }
    }

    override func viewDidLoad() {
        super.viewDidLoad()
        self.getPermission()
        locationManager = CLLocationManager()
        locationManager!.desiredAccuracy = kCLLocationAccuracyBest
        locationManager?.startUpdatingLocation()
    }
}
塞缪尔·海登(Samuel Hayden)

正如ohr所指出的,还需要额外的许可。将以下行添加到了懒惰的locationManager初始化程序中,以纠正此遗漏:

manager.allowsBackgroundLocationUpdates = true

按照Noah和Paulw11的建议,删除了getPermission函数,该行:

locationManager = CLLocationManager()

已从viewDidLoad中删除,因为存在大量冗余。仅此一项并不能解决问题,而是将逻辑添加到locationManager函数中,以便将最新的地图数据存储到数组中,如下所示:

let annotation = MKPointAnnotation()
annotation.coordinate = newLocation.coordinate    
locations.append(annotation)
while locations.count > 100 {
    let annotationToRemove = locations.first!
    locations.remove(at: 0)
}

导致工作代码。该解决方案源自以下代码:https : //www.raywenderlich.com/92428/background-modes-ios-swift-tutorial(感谢Ray)

最终,代码可以在前台和后台运行,而无需从类中删除任何内容或在appdelegate中实现任何功能。

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章