N分钟后连续位置跟踪ios

disbfnqx  于 9个月前  发布在  iOS
关注(0)|答案(1)|浏览(87)

有没有人在iOS中实现了后台位置更新的任何帮助将是伟大的下面是我的情况

问题陈述

  • 我想跟踪用户的位置后,每N分钟,并将其发送到服务器(无论是案件背景和杀害状态)

我一直在努力

  • 启用后台模式、位置更新、后台提取和后台处理
  • 创建了一个用于位置跟踪的单例检查下面的代码,并在

使用选项启动- AppDelegate
现在我已经探索了 * BakcgroundTasks*,但后台任务已注册,但在给定的时间间隔后未执行,请检查下面的代码

class EmployeeAttendanceTracker: NSObject,CLLocationManagerDelegate {

    
   static let shared = EmployeeAttendanceTracker()

    private let locationManager = CLLocationManager()
    private var lastLocationDate = Date()
    static let LOCATION_INTERVAL = 1
    
    var locationUpdate: (() -> Void)?

    private override init() {
        super.init()
        setupLocationManager()
    }
    
    private func setupLocationManager() {
        locationManager.delegate = self
        locationManager.desiredAccuracy = kCLLocationAccuracyBest
        locationManager.activityType = .other
        locationManager.distanceFilter = kCLDistanceFilterNone
        locationManager.allowsBackgroundLocationUpdates = true
        locationManager.pausesLocationUpdatesAutomatically = false
        locationManager.showsBackgroundLocationIndicator = true
        
        
        if #available(iOS 9.0, *) {
          locationManager.requestAlwaysAuthorization()
        } else {
          locationManager.requestWhenInUseAuthorization()
        }
    }
      //    
    //
    //    // MARK: - CLLocationManagerDelegate
    //    
        func locationManager(_ manager: CLLocationManager, didChangeAuthorization      status: CLAuthorizationStatus) {
            switch status {
            case .restricted:
                //showLocationPermissionAlert()
                Logger.s("Location access restricted.")
            case .denied:
                //showLocationPermissionAlert()
                Logger.s("User denied location access.")
            case .notDetermined:
               // showLocationPermissionAlert()
                Logger.s("Location access not determined.")
            case .authorizedAlways:
                if #available(iOS 9, *) {
                    locationManager.requestLocation()
                } else {
                    locationManager.startUpdatingLocation()
                    locationManager.startMonitoringSignificantLocationChanges()
                }
            default:
               // showLocationPermissionAlert()
                break
            }
        }

    func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
    guard let location = locations.last else { return }
    
    Logger.s("User latitude: \(location.coordinate.latitude), longitude: \(location.coordinate.longitude)")
    locationManager.stopUpdatingLocation()
    
    let now = Date()
    if isItTime(now: now as NSDate) {
        if shouldSendLocationToServer() {
            self.sendLocationToServer(location: location,completion: {
                self.locationUpdate?()
            })
        }else{
            self.locationUpdate?()
        }
        Logger.s(now)
        Logger.s(location)
    }else{
        self.locationUpdate?()
    }
    
}

字符串
AppDelegate.swift

func scheduleAppRefresh() {
      let request = BGAppRefreshTaskRequest(identifier: "com.example.location_update")
      request.earliestBeginDate = Date(timeIntervalSinceNow: 15 * 60) // 15 minutes from now
      
      do {
          try BGTaskScheduler.shared.submit(request)
          Logger.s("BG TASK REQUEST SUBMITTED")
      } catch {
          print("Unable to submit task request: \(error)")
      }
  }

func handleAppRefresh(task: BGAppRefreshTask) {
     task.expirationHandler = {
         // Handle expiration if needed
         Logger.s("BG TASK EXPIRED")
         task.setTaskCompleted(success: false)
     }
   Logger.s("HANDLE BG TASK REQUEST")
    EmployeeAttendanceTracker.shared.locationUpdate = {
         task.setTaskCompleted(success: true)
     }
 }

 func registerBackGroundTasks()  {
    // Register for background tasks
    BGTaskScheduler.shared.register(
        forTaskWithIdentifier: "com.example.location_update",
        using: DispatchQueue.global()
    ) { task in
        // Your task handler logic
        //task.setTaskCompleted(success: true)
        self.handleAppRefresh(task: task as! BGAppRefreshTask)
    }
}

csbfibhn

csbfibhn1#

你不能这样做。至少不能用后台刷新任务。应用程序刷新任务将在iOS选择时执行。earliestBeginDate正是这样;任务将运行的最早时间。它可能在该日期后几分钟,几小时或几天运行。
你可以采取以下几种策略:
1.使用具有“始终”权限的startUpdatingLocation。这将大约每秒提供一次位置更新。然后,您可以每“n”分钟向服务器报告一次位置。这将对电池产生重大影响,并且如果应用被终止,将不会重新启动应用。
1.使用 * 显著位置变化监控 *。这将仅在用户移动了约500米时提供位置更新。如果用户正在步行或停留一段时间,则这可能长于“n”分钟,或者如果用户正在快速移动,则可能比“n”分钟更频繁(比如在汽车或火车上)。重要的位置监控使用更少的电力,并且如果它被终止,将允许您的应用重新启动(只有在检测到重要的位置变化时)。
1.使用一个组合;经常更新的定期位置和重要的位置更新,以重新启动,如果终止。
使用哪种方法取决于应用的用例。
对于Uber风格的“驱动程序”应用程序,您希望持续更新,并且有理由期望设备连接到外部电源。
对于Uber风格的“骑手”应用程序,您希望持续更新,但只需要很短的时间(从预订过程开始直到接人),因此电力消耗可能不是问题。
对于其他用例,请考虑位置变化本身是否足够。

相关问题