location in the background does not work - ios

I am developing a code that should get my location every 10 minutes and salvation in CoreData. When I walk into background with conectavo app to xcode can not see the log that the service is running, but when I go out walking the streets he simply not saved or saved too few times.
This is part of my code that should do this function.See save in codeData:
var saveLocationInterval = 60.0
func applicationDidEnterBackground(application: UIApplication) {
UIApplication.sharedApplication().beginBackgroundTaskWithExpirationHandler(nil)
self.timer = NSTimer.scheduledTimerWithTimeInterval(saveLocationInterval, target: self, selector: #selector(AppDelegate.saveLocation), userInfo: nil, repeats: true)
NSRunLoop.currentRunLoop().addTimer(self.timer, forMode: NSRunLoopCommonModes)
locationController.startUpdatingLocation()
}
func locationManager(manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
saveLocation()
}
func saveLocation(){
print("======")
let logUser = NSEntityDescription.insertNewObjectForEntityForName("LOG_GPS", inManagedObjectContext: self.managedObjectContext) as! LOG_GPS
if locationController.location == nil{
logUser.latitude = ""
logUser.longitude = ""
} else {
logUser.latitude = "\(locationController.location!.coordinate.latitude)"
logUser.longitude = "\(locationController.location!.coordinate.longitude)"
}
logUser.velocidade = userSpeed > 0 ? Int(userSpeed) : 0
logUser.address = "\(userSpeed)"
if _usuario.chave != nil {
logUser.chave_usuario = "\(_usuario.chave!)"
}
if _empresa.chave != nil {
logUser.chave_licenca = "\(_empresa.chave!)"
}
print("localizaçao salva no bd \(logUser.latitude)")
let date = NSDate()
let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "dd/MM/yy HH:mm:ss"
let dateString = dateFormatter.stringFromDate(date)
logUser.data = dateString
do {
try self.managedObjectContext.save()
} catch {
}
}
Another major error in my code I can not solve is the User's speed. In the method the low I'm trying to save your speed in a variable and then save the CoreData however this is me always returning a negative value:
func locationManager(manager: CLLocationManager, didUpdateToLocation newLocation: CLLocation, fromLocation oldLocation: CLLocation) {
var speed: CLLocationSpeed = CLLocationSpeed()
speed = newLocation.speed
print(speed * 3.6)
userSpeed = speed * 3.6
}
this is my background mode

Possible solution 1
You need a key in your Info.plist that describes why your app needs background location.
Go to your Info.plist, find the Bundle Version key and click the + that appears when you hover over that. Then add the key NSLocationAlwaysUsageDescription, set it to be a string, and set the value as whatever you want the description to be, like "We need your location in the background so we share your location with friends."
Now your app should work. If it doesn't....
Possible solution 2 (more likely solution if you know what you're doing)
With iOS 9, Apple made it so that apps on physical devices need a special line of code to run location services in the background. The change was not widely reported on (if at all?) but I managed to figure this one out a while ago. Here's what you need to do to get location services working in the background on physical devices again:
In your main location tracking view controller's ViewDidLoad put...
if #available(iOS 9.0, *) {
locationManager.allowsBackgroundLocationUpdates = true
} else {
// You don't need anything else on earlier versions.
}
This will (mysteriously enough) likely be all you need to solve your problem.

Related

CLFloor returns level 2146959360?

I’m using CLLocationManager, looking at the location property and examining the level of the floor, if any. The documentation suggests that if it couldn’t determine the floor, that it would just return nil. In practice, I am getting a CLFloor instance, but its level is 2146959360. Converting that to hex, 0x7FF80000, which looks suspiciously like some cryptic sentinel value.
lazy var locationManager: CLLocationManager = {
let locationManager = CLLocationManager()
locationManager.delegate = self
locationManager.desiredAccuracy = kCLLocationAccuracyBest
return locationManager
}()
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
switch CLLocationManager.authorizationStatus() {
case .notDetermined: locationManager.requestWhenInUseAuthorization()
case .denied: redirectToSettings()
default: break
}
}
#IBAction func didTapGetLocation(_ sender: Any) {
updateLabels(for: locationManager.location)
}
func updateLabels(for location: CLLocation?) {
guard let location = location else {
floorLabel.text = "No location."
return
}
if let floor = location.floor {
let hexString = "0x" + String(format: "%08x", floor.level)
floorLabel.text = "\(floor.level) (\(hexString))"
} else {
floorLabel.text = "No floor."
}
}
I’m seeing this behavior in on a physical iOS 13.3.1 devices, only. FWIW, older iOS versions (I’ve only got iOS 10 device sitting here) appear to return nil, as expected, as does the simulator.
What’s going on?
This problem goes away if you call startUpdatingLocation. If you do that, then the floor property will be nil. This CLFloor instance with a level value of 2146959360 (0x7FF80000) only appears if you query the location of the CLLocationManager without having first called startUpdatingLocation.
The documentation suggests that this location property is populated with the last known value. Regardless, the floor should be nil (for my particular location, at least) but isn’t. The level is invalid.
See this repo for example of manifestation of the bug and demonstration of how calling startUpdatingLocation works.
I’ve filed a bug report (FB7638281).

Update location when user is in background - swift

I've had an issue for like 3-4 months. I've tried everything you can ever imagine to get this to work, but I really can't. Now I'm looking for your help to fix this issue.
I've an application, when you press a start button it should get locations. (Works perfectly fine when ur on the application.)
But once you leave the application, (not killing the process) and goes to the background. The polyline is not drawing like it should. It pauses or something.
I need someone either who can help me here, or create a chatroom with me so we can discuss and I will send the rest of the code.
Here is parts of it, which I think is the most important.
Inside the viewDidLoad
let app = UIApplication.shared
NotificationCenter.default.addObserver(self, selector: #selector(applicationWillResignActive(notification:)), name: UIApplication.willResignActiveNotification, object: app)
NotificationCenter.default.addObserver(self, selector: #selector(didBecomeActive(notification:)), name: UIApplication.didBecomeActiveNotification, object: app)
-
#objc func applicationWillResignActive(notification: NSNotification)
{
start = CFAbsoluteTimeGetCurrent()
print("Background entered")
startReceivingSignificantLocationChanges()
}
#objc func didBecomeActive(notification: NSNotification)
{
let elapsed = CFAbsoluteTimeGetCurrent() - start
counter = counter + Int(elapsed)
print("Returned to application")
locationManager.stopMonitoringSignificantLocationChanges()
}
< Inside the start button.
//Checking userpermission to allow map and current location
if (CLLocationManager.locationServicesEnabled())
{
locationManager.requestAlwaysAuthorization()
locationManager.requestWhenInUseAuthorization()
self.locationManager.allowsBackgroundLocationUpdates = true
self.locationManager.showsBackgroundLocationIndicator = true
//Retrieve current position
if let userLocation = locationManager.location?.coordinate
{
//Zooming in to current position
let viewRegion = MKCoordinateRegion(center: userLocation, latitudinalMeters: 200, longitudinalMeters: 200)
mapView.setRegion(viewRegion, animated: false)
//Creating a start annotation
if locations.isEmpty
{
let annotation = MKPointAnnotation()
annotation.title = "Start"
annotation.coordinate = userLocation
mapView.addAnnotation(annotation)
}
self.locations.append(userLocation)
print(self.locations, "First")
//Starts the walk-timer, with interval: 1 second
timer = Timer.scheduledTimer(timeInterval: 1, target: self, selector: #selector(updateCounter), userInfo: nil, repeats: true)
//Sending to update
update()
}
}
< Background worker
func startReceivingSignificantLocationChanges()
{
let authorizationStatus = CLLocationManager.authorizationStatus()
if authorizationStatus != .authorizedAlways
{
return
}
if !CLLocationManager.significantLocationChangeMonitoringAvailable()
{
// The service is not available.
return
}
else
{
locationManager.desiredAccuracy = kCLLocationAccuracyHundredMeters
locationManager.distanceFilter = 100.0 //100.0 meters
locationManager.activityType = .fitness
locationManager.allowsBackgroundLocationUpdates = true
locationManager.delegate = self
locationManager.startMonitoringSignificantLocationChanges()
}
}
func locationManager(_ manager: CLLocationManager, didUpdateLocations
locations: [CLLocation])
{
let lastLocation = locations.last!
self.locations.append(lastLocation.coordinate)
print("Locations retrieved from background: ", self.locations)
}
There is a lot more I've to show you. But unfortunately it would be way too much...
Please enable the Background Modes from the capabilities of the project and enable the 'Location updates'. After enabling this, the only configuration to get the updates in the background(not in killed state) is to set'allowsBackgroundLocationUpdates' to true(which you have done already).
Here the significant location changes are only needed when you want to get the location when the application is killed by the user. This significant location change will launch the application in background and read the location of the device. For more information on getting location in the background follow :
https://developer.apple.com/documentation/corelocation/cllocationmanager/1620568-allowsbackgroundlocationupdates
For significant location changes while the application is in killed state, follow below link. This is in objective C but it can be easily done in swift also.
http://mobileoop.com/getting-location-updates-for-ios-7-and-8-when-the-app-is-killedterminatedsuspended
Hope this helps.

iOS debug location monitoring when app is closed from simulator

It seems that my app is not launched and called with location updates when it is in a terminated state.
Since it is a little bit hard for me to test what is not working (using a real device is not really easy when you have to move back and forth inside an office trying to trigger a significant location change), is there a way to simulate location changes in the simulator while the app is closed?
I have already tried using the Simulator > Debug > Location > [City Bicyce Ride, ...] but it seems that it works only when the app is running. I even tried creating a scheme where the app is not launch automatically after compiling.
Do you have any suggestion on how to debug this kind of issues?
(By now I am just logging on separate files at every application launch, even though unfortunately the app gets not launched in background when is in a closed state )
This is the code in my app delegate:
lazy var locationManagerFitness: CLLocationManager! = {
let manager = CLLocationManager()
manager.desiredAccuracy = kCLLocationAccuracyBest
manager.distanceFilter = 1.0
manager.activityType = CLActivityType.Fitness
manager.delegate = self
manager.requestAlwaysAuthorization()
return manager
}()
func startLocationMonitoring()
{
locationManagerFitness.stopMonitoringSignificantLocationChanges()
locationManagerFitness.startUpdatingLocation()
}
func startLocationMonitoringSignificantChanges()
{
locationManagerFitness.stopUpdatingLocation()
locationManagerFitness.startMonitoringSignificantLocationChanges()
}
// MARK: - CLLocationManagerDelegate
func locationManager(manager: CLLocationManager, didUpdateLocations locations: [CLLocation])
{
if manager == locationManagerFitness
{
log.debug("locationManagerFitness:")
}
for newLocation in locations
{
saveLocation(newLocation)
if UIApplication.sharedApplication().applicationState == .Active {
log.debug("App is active. New location is \( newLocation )")
} else {
log.debug("App is in background. New location is \( newLocation )")
}
}
}
func saveLocation(location: CLLocation) -> Location {
let entity = NSEntityDescription.entityForName("Location",
inManagedObjectContext:managedObjectContext)
let locationCD = NSManagedObject(entity: entity!,
insertIntoManagedObjectContext: managedObjectContext) as! Location
locationCD.setValue(location.coordinate.latitude, forKey: "latitude")
locationCD.setValue(location.coordinate.longitude, forKey: "longitude")
locationCD.setValue(NSDate(), forKey: "creationDate")
do {
try managedObjectContext.save()
} catch let error as NSError {
print("Could not save \(error), \(error.userInfo)")
}
return locationCD
}
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?)
-> Bool {
//Logs
let documentDirectoryURL = try! NSFileManager.defaultManager().URLForDirectory(.DocumentDirectory, inDomain: .UserDomainMask, appropriateForURL: nil, create: true)
let dayTimePeriodFormatter = NSDateFormatter()
dayTimePeriodFormatter.dateFormat = "hh:mm_dd-MM-yyyy"
let dateString = dayTimePeriodFormatter.stringFromDate(NSDate())
let logURL = documentDirectoryURL.URLByAppendingPathComponent("log_\( dateString ).txt")
log.setup(.Debug, showThreadName: true, showLogLevel: true, showFileNames: true, showLineNumbers: true, writeToFile: logURL, fileLogLevel: .Debug)
log.debug("Starting app...")
// StatusBar
UIApplication.sharedApplication().statusBarStyle = .LightContent
switch CLLocationManager.authorizationStatus()
{
case .AuthorizedAlways:
if let _ = launchOptions?[UIApplicationLaunchOptionsLocationKey]
{
startLocationMonitoringSignificantChanges()
}
default:
break;
}
log.debug("App started!")
return true
}
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.
log.debug("startLocationMonitoringSignificantChanges")
startLocationMonitoringSignificantChanges()
}
func applicationDidBecomeActive(application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
log.debug("startLocationMonitoring")
startLocationMonitoring()
}
The behavior of the above code is that the app is monitoring user location changes only when it is active.
Looking the image below is clear that the simulator seems to continue to move the location of the Bicycle Ride, however the AppDelegate CLLocationManagerDelegate's locationManager(manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) is not called while the app is terminated or in background:
Did you tried the custom Location instead of City Bycle Ride? One of my app I used Region Monitoring and if I give manually the locations then it is work even if i lock the simulator.

Process location data in the background

I am currently receiving location updates and want to periodically send an update to a server via an api call. Everything works when launching the app but updates in the background are really inconsistent.
Here's what I'm currently trying to do:
var lastUpdateTime: Double?
func locationManager(manager: CLLocationManager, didUpdateToLocation newLocation: CLLocation, fromLocation oldLocation: CLLocation)
{
userLocation = newLocation
if let lastUpdate = lastUpdateTime {
let thisUpdate = NSDate().timeIntervalSince1970
let timeInterval = thisUpdate - lastUpdate
if timeInterval > 60 {
if
let latitude = userLocation?.coordinate.latitude,
let longitude = userLocation?.coordinate.longitude
{
// Make API call to update location
lastUpdateTime = NSDate().timeIntervalSince1970
}
}
} else {
lastUpdateTime = NSDate().timeIntervalSince1970
}
}
I've read what I can find regarding background tasks and location updates but honestly I'm a bit lost. If it helps, the api call is made through Alamofire if that has an effect on how often it gets executed.
EDIT:
Added CLLocationManager options...
locationManager.delegate = self
locationManager.distanceFilter = kCLDistanceFilterNone
locationManager.desiredAccuracy = kCLLocationAccuracyNearestTenMeters
locationManager.startUpdatingLocation()
For getting location updates in background , app should enable 'location update' background mode in capabilities tab in project settings.
Apart from this, required background location key(NSLocationAlwaysUsageDescription) needs to be added into the info.plist file. If these two things are done correctly, app will receive location updates continuously in background when call 'startUpdatingLocation'

Standard Location based iOS app not waking up after suspended IOS

I am developing a location based app which is supposed to fetch user location always.Im using standard location service. But the problem is that the app after keeping idle for some time in background will not fetch the coordinates even after we move to some other locations. As per apple documentation, when a new location arrives, app should wake up automatically, but that is not happening here. I'm sharing the code and using to fetch location and screenshot of my plist.
class SALocation: NSObject,CLLocationManagerDelegate
{
static let sharedInstance : SALocation = SALocation()
var locationManager : CLLocationManager!
var location : CLLocation!
var address : String!
var latitude : NSString?
var longitude : NSString?
var isAdderssLoaded : Bool = false
var locdictionary : NSMutableDictionary = NSMutableDictionary()
func startLocationManager()
{
if self.locationManager == nil
{
self.locationManager = CLLocationManager()
if CLLocationManager.locationServicesEnabled(){
print("location service enabled")
}
self.locationManager.delegate = self
self.locationManager.requestWhenInUseAuthorization()
self.locationManager.distanceFilter = kCLDistanceFilterNone
self.locationManager.desiredAccuracy = kCLLocationAccuracyBest
if ( Float (UIDevice.currentDevice().systemVersion) >= 9) {
if #available(iOS 9.0, *) {
self.locationManager.allowsBackgroundLocationUpdates = true
} else {
// Fallback on earlier versions
};
}
self.locationManager.startUpdatingLocation()
//self.locationManager.stopMonitoringSignificantLocationChanges()
}
else
{
self.locationManager.startUpdatingLocation()
}
}
// MARK: CLLocationManagerDelegate
func locationManager(manager: CLLocationManager, didFailWithError error: NSError)
{
UIAlertView(title:"Alert", message:error.description, delegate: nil, cancelButtonTitle:nil, otherButtonTitles:"Ok").show()
}
func locationManager(manager: CLLocationManager, didUpdateLocations locations: [CLLocation])
{
if locations.count > 0
{
self.location = locations[0]
/* storing date and location to plist
*/
let datenow = NSDate()
let dateformatternow = NSDateFormatter ()
dateformatternow.dateFormat = "yyyyMMdd HH:mm:ss"
let timenow:NSString = dateformatternow.stringFromDate(datenow)
let documetsdirectorypath = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.UserDomainMask, true).last
latitude = NSString(format: "%f",self.location.coordinate.latitude)
longitude = NSString (format: "%f",self.location.coordinate.longitude)
let latlong : NSString = NSString(format:"%#~%#",latitude!,longitude!)
NSUserDefaults.standardUserDefaults().setObject(latlong, forKey: "latlong")
let aFilePath = NSString(format: "%#/location.plist",documetsdirectorypath!)
locdictionary.setObject(latlong, forKey: timenow as String)
locdictionary.writeToFile(aFilePath as String, atomically: true)
///////////// ||storing date and location to plist code ends here||\\\\\\
// self.getAddressFromLocation(locations[0] )
// if (NSUserDefaults.standardUserDefaults().objectForKey(SettingAppRefresh) != nil)
// {
// if (NSUserDefaults.standardUserDefaults().objectForKey(SettingAppRefresh) as! NSString).isEqualToString(FalseString)
// {
// // self.locationManager.stopUpdatingLocation()
// }
// }
}
}
}
What i'm doing here is just get location and write it to a plist file. This works in foreground, background etc fine. But when i keep the app idle for 20 minutes, location is not fetched even if i move to some other locations as the app is suspended
Capabilities tab looks like this
To start location in background you must start background service from the following path
Click on your name -> Click on your app name (target) -> goto capabilities -> find the background mode -> enable the location update mode
I am not sure you started that or not because you not put any screenshot about this.
And also check that your user started background refresh in settings.refer below link for this.
Background App Refresh checking, enabling and disabling programatically for whole device and for each particular application in iOS 7
Update::
For location update in background used below link(objective c)
http://www.creativeworkline.com/2014/12/core-location-manager-ios-8-fetching-location-background/
Well, I don't know how you're getting location updates - significant-location change as example and how you exit from background.
I suggest checking if your app is truly in background mode - UIApplication.sharedApplication().applicationState as it can be terminated.
And I also suggest checking out Apple's Execution States for Apps. - especially for your possible use case Implementing Long-Running Tasks part. There is also a good tutorial at rayywenderlich.com called Background modes.
Please use
self.locationManager.requestAlwaysAuthorization()
and don't forget to update your Info.plist to define the NSLocationAlwaysUsageDescription key.

Resources