Send Location of User in Background Swift

前端 未结 3 1342
名媛妹妹
名媛妹妹 2021-01-03 13:54

I am building an app where the user clicks a button and for 60mins (or any amount of time) we keep track of them by uploading their location to a server. Currently we are us

3条回答
  •  借酒劲吻你
    2021-01-03 14:15

    import UIKit
    import CoreLocation
    @UIApplicationMain
    
    class AppDelegate: UIResponder, UIApplicationDelegate,CLLocationManagerDelegate {
    var window: UIWindow?
    var locationManager = CLLocationManager()
    var backgroundUpdateTask: UIBackgroundTaskIdentifier!
    var bgtimer = Timer()
    var latitude: Double = 0.0
    var longitude: Double = 0.0
    var current_time = NSDate().timeIntervalSince1970
    var timer = Timer()
    var f = 0
    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
        self.doBackgroundTask()
        return true
    }
    
    
    func applicationWillResignActive(_ application: UIApplication) {
    }
    
    func applicationWillEnterForeground(_ application: UIApplication) {
        print("Entering foreBackground")
    }
    
    func applicationDidBecomeActive(_ application: UIApplication) {
    }
    
    func applicationWillTerminate(_ application: UIApplication) {
    }
    
    func applicationDidEnterBackground(_ application: UIApplication) {
        print("Entering Background")
       // self.doBackgroundTask()
    }
    
    func doBackgroundTask() {
    
        DispatchQueue.main.async {
    
            self.beginBackgroundUpdateTask()
    
            self.StartupdateLocation()
    
    
            self.bgtimer = Timer.scheduledTimer(timeInterval:-1, target: self, selector: #selector(AppDelegate.bgtimer(_:)), userInfo: nil, repeats: true)
            RunLoop.current.add(self.bgtimer, forMode: RunLoopMode.defaultRunLoopMode)
            RunLoop.current.run()
    
            self.endBackgroundUpdateTask()
    
        }
    }
    
    func beginBackgroundUpdateTask() {
        self.backgroundUpdateTask = UIApplication.shared.beginBackgroundTask(expirationHandler: {
            self.endBackgroundUpdateTask()
        })
    }
    
    func endBackgroundUpdateTask() {
        UIApplication.shared.endBackgroundTask(self.backgroundUpdateTask)
        self.backgroundUpdateTask = UIBackgroundTaskInvalid
    }
    
    func StartupdateLocation() {
        locationManager.delegate = self
        locationManager.desiredAccuracy = kCLLocationAccuracyBest
        locationManager.distanceFilter = kCLDistanceFilterNone
        locationManager.requestAlwaysAuthorization()
        locationManager.allowsBackgroundLocationUpdates = true
        locationManager.pausesLocationUpdatesAutomatically = false
        locationManager.startUpdatingLocation()
    }
    
    func locationManager(_ manager: CLLocationManager, didFailWithError error: Error) {
        print("Error while requesting new coordinates")
    }
    
    func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
    
        let locValue:CLLocationCoordinate2D = manager.location!.coordinate
    
        self.latitude = locValue.latitude
        self.longitude = locValue.longitude
        f+=1
        print("New Coordinates: \(f) ")
        print(self.latitude)
        print(self.longitude)
    }
    
    @objc func bgtimer(_ timer:Timer!){
        sleep(2)
      /*  if UIApplication.shared.applicationState == .active {
             timer.invalidate()
        }*/
        self.updateLocation()
    }
    
    func updateLocation() {
        self.locationManager.startUpdatingLocation()
        self.locationManager.stopUpdatingLocation()
    }}
    

    I added the sleep function to delay of calling the location and send the information to server

    Since this is running in both the app is active and goes to background. If you want only background process, remove or comment the function self.doBackgroundTask() from didFinishLaunchingWithOptions and remove the comment for self.doBackgroundTask() in the applicationdidEnterBackground. And then remove the comment in the function bgtimer(), since the background process has to stop once the app comes to active state.

提交回复
热议问题