简体   繁体   中英

How Can I Continue updating my location even when app is killed or removed from background in ios?

My app requires to update location continuously, even if app is killed or removed from background. It works fine in foreground and even in background mode.but not working when app is killed. I've tried some code.

func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {

    self.startLocationService()

    if ((launchOptions?[UIApplicationLaunchOptionsLocationKey]) != nil) {
       self.locationmanager = CLLocationManager()
        self.startLocationService()
    }

    print("Location Updates started")


    return true
}

func startLocationService()
{
    self.locationmanager.requestWhenInUseAuthorization()
    self.locationmanager.desiredAccuracy = kCLLocationAccuracyBest
    self.locationmanager.allowsBackgroundLocationUpdates = true
    self.locationmanager.requestAlwaysAuthorization()
    self.locationmanager.delegate = self


    if UIApplication.sharedApplication().backgroundRefreshStatus == .Available {
        print("Background updates are available for the app.")

    }
    else if UIApplication.sharedApplication().backgroundRefreshStatus == .Denied {
        print("The user explicitly disabled background behavior for this app or for the whole system.")

    }
    else if UIApplication.sharedApplication().backgroundRefreshStatus == .Restricted {
        print("Background updates are unavailable and the user cannot enable them again. For example, this status can occur when parental controls are in effect for the current user.")

    }
    else
    {
        print("nothing")
    }

    self.locationmanager.startUpdatingLocation()
}



func applicationDidEnterBackground(application: UIApplication) {
    // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
    // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
   // locationManager = CLLocationManager()
        }

  func applicationDidBecomeActive(application: UIApplication) {

    self.startLocationService()
}

func applicationWillTerminate(application: UIApplication) {      
             self.locationmanager.startMonitoringSignificantLocationChanges()

}


func locationManager(manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
     print("did update locateion called-->..")
    let location:CLLocation = locations[locations.count-1] 

    print(location.coordinate.longitude)
      print(location.coordinate.latitude)

    let newTime : NSDate = NSDate()

    let calendar: NSCalendar = NSCalendar.currentCalendar()
    let flags = NSCalendarUnit.Second
    let components = calendar.components(flags, fromDate: oldTime, toDate: newTime, options: [])


   //Update locations to server 
    self.call_service_insertLocation("location", loc: location)

}


func locationManager(manager: CLLocationManager, didFailWithError error: NSError) {
    print(error)
}

I hope this might help you. Your app can be awaken when it is terminated by some reason (Memory pressure).

But there's limitation on background location update when app is terminated.

This is note from Apple's Location and Map programming guide.

If your app is terminated either by a user or by the system, the system doesn't automatically restart your app when new location updates arrive. A user must explicitly relaunch your app before the delivery of location updates resumes. The only way to have your app relaunched automatically is to use region monitoring or significant-change location service . However, when a user disables the Background App Refresh setting either globally or specifically for your app, the system doesn't relaunch your app for any location events, including significant change or region monitoring events. Further, while Background App Refresh is off your app won't receive significant change or region monitoring events even when it's in the foreground.

So to receive location update in background, you should turn on Background App Refresh setting for your app (You can see the setting in Settings/Your App/Background App Refresh in your iPhone.)

Also only significant changes will be delivered when app is terminated and like location changes you mentioned here (I mean kCLLocationAccuracyBest ) probably will not wake your app. Further more, you should restart the location manager in your app delegate s application:didFinishLaunching:withOptions method to retrieve next significant location changes. Also make sure return as soon as possible when location is retrieved in background mode or use background task mechanism to make app working more a few minutes in background. (2~3 mins).

Its possible, but you'll have to jump through a few hoops. The only way to send location updates when killed is by using Region Monitoring ( https://developer.apple.com/library/ios/documentation/UserExperience/Conceptual/LocationAwarenessPG/RegionMonitoring/RegionMonitoring.html ). When setup up, your app would be opened by the OS then you have a few seconds to process information before the app is killed. Its enough time to send location updates to your server/local storage. There is also another API called CLVisit, however, its completely controlled by the operating system and not reliable.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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