iOS update location after kill app from Background - ios

In my project, I want to track user location. For that i want to update user current location based on location accuracy(for High-> 15 min and Low -> 1 hour). When application run or in background than I can update location but after kill application from background, can't update location. I used timer to call it but after kill app(from background), it's not work.
So now what i do to update location based on location accuracy if user not run app in background also.
Please give any suggestion.

CoreLocation has 2 permisson:
One is for when the user use the app.
The second is updating location always even if it is not in used.
Use the second one, that's what GPS use for instance. But if you kill the app that is a going to stop updating location.

You need to add the NSLocationAlwaysUsage keys to your apps info.plist and then request permission when you wish to start monitoring.
Make sure you give a good description of why you want to always monitor bc I feel that really helps conversion rates.

locationManager = [[CLLocationManager alloc] init];
#define IS_OS_8_OR_LATER ([[[UIDevice currentDevice] systemVersion] floatValue] >= 8.0)
if(IS_OS_8_OR_LATER)
{
[locationManager requestWhenInUseAuthorization];
}
locationManager.delegate = self;
locationManager.distanceFilter = kCLDistanceFilterNone; //whenever we move
locationManager.desiredAccuracy = kCLLocationAccuracyHundredMeters;
[locationManager startUpdatingLocation];
that code user location update only forground app running but not background run
if(IS_OS_8_OR_LATER)
{
[locationManager requestWhenInUseAuthorization];
}

Related

Latidude and Longitude are incorrect first time app is launched ios

I am using CLLocationManager to get the user's current location. I need the user's current location because I am using the Open Weather Api to display the weather data wherever the user is. My problem is that the first time I open the app the lat and long value are 0, 0. But then if I run the app again it works fine. So only on the first launch of the app incorrect lat and long values are used. I do all my set up in viewDiDLoad, here is the code...
locationManager = [[CLLocationManager alloc] init];
[locationManager requestAlwaysAuthorization];
locationManager.delegate = self;
locationManager.desiredAccuracy = kCLLocationAccuracyBest;
if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 8.0)
[self->locationManager requestWhenInUseAuthorization];
[locationManager startUpdatingLocation];
I don't know what I am doing wrong. Is it something to do with getting the lat and long in the view controller instead of App Delegate?
Here is how I am getting the location values:
locationManager.location.coordinate.latitude
locationManager.location.coordinate.longitude
It's happening because when you launch your app first time Location manager asks for user permission to access current location and when user allows - It takes little time in process of fetching current location and you're accessing coordinates before completion of that process.
When you launch your app again Location manager detects that you already gave the permission so it gives you current location coordinate very quickly.
So the solution is - you've to wait until it completes location update opt. You can put some kinda delay there using dispatch OR can use Location manager delegate method didUpdateUserLocation OR if your UIViewController isn't the initial view controller - in this case you should implement this process in AppDelegate, use your code in didFinishLaunching, so when you'll open your view controller (whatever navigation flow you're using) location details will be there cause in meantime location manager will track your location.
Hope it'll help you!
You should check horizontalAccuracy of the CLLocation object for a negative value and do not use the lat/lon value if that is the case. It is highly likely that when you see the lat/lon values are 0/0, the GPS hasn't secured a location lock.

Getting wrong coordinates when tracked via Cellular in iOS

I am getting wrong coordinates using cellular data, but when I am using wifi it's getting currect coordinates. I am fetching coordinates using CLLocationManager. I have struck from one month. Thanks a lot in advance.
self.locationManagerForCheckIn=[[CLLocationManager alloc] init];
self.locationManagerForCheckIn.delegate = self;
self.locationManagerForCheckIn.distanceFilter = kCLDistanceFilterNone;
self.locationManagerForCheckIn.desiredAccuracy = kCLLocationAccuracyBest;
if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 8.0)
[self.locationManagerForCheckIn requestWhenInUseAuthorization];
[self.locationManagerForCheckIn startUpdatingLocation];
I think its a common issue with cllocation the actual accuracy is not guaranteed. as documentation
When requesting high-accuracy location data, the initial event
delivered by the location service may not have the accuracy you
requested. The location service delivers the initial event as quickly
as possible. It then continues to determine the location with the
accuracy you requested and delivers additional events, as necessary,
when that data is available.
my suggesions for best results
locationManager.desiredAccuracy = kCLLocationAccuracyBestForNavigation;
and please check this also locationmanager responsiveness

Location Notification's based on Latest iOS Feature

I would like to know whether the following is implementable ?
I want my iOS app to give users a notification when the reach a particular location as set in the app (even if the app is killed)
You can achieve this with the new User Notification framework introduced in iOS 10.
There have a UNLocationNotificationTrigger which let you specify a CLRegion. A notification will be post when the user’s device enters or leaves the CLRegion. Use the CLRegion object to specify whether to deliver notifications on entry, on exit, or both.
Refer to:
UserNotifications framework:
https://developer.apple.com/reference/usernotifications
UNLocationNotificationTrigger:
https://developer.apple.com/reference/usernotifications/unlocationnotificationtrigger
When the app is killed you can't , but you can still do it in background mode.
First Way:
UNLocationNotificationTrigger notifies user when user enters the specified location or exit the specified location this link provides exact implementation.
Second Way:
monitoring significant changes can do this for you but the result may not be 100%.
call following method from applicationDidEnterBackground and applicationWillTerminate:;
- (void)startSignificantChangeUpdates
{
// Create the location manager if this object does not
// already have one.
if (nil == locationManager)
locationManager = [[CLLocationManager alloc] init];
locationManager.delegate = self;
[locationManager startMonitoringSignificantLocationChanges];
}
and when app enters foreground applicationWillEnterForeground: call following method (modify it as per your requirements i.e. accuracy & distance filter)
- (void)startStandardUpdates
{
// Create the location manager if this object does not
// already have one.
if (nil == locationManager)
locationManager = [[CLLocationManager alloc] init];
locationManager.delegate = self;
locationManager.desiredAccuracy = kCLLocationAccuracyKilometer;
// Set a movement threshold for new events.
locationManager.distanceFilter = 500; // meters
[locationManager startUpdatingLocation];
}
From apple documentation:
The significant-change location service delivers updates only when there has been a significant change in the device’s location, such as 500 meters or more. It’s crucial that you use the significant-change location service correctly, because it wakes the system and your app at least every 15 minutes, even if no location changes have occurred, and it runs continuously until you stop it.
For 100% accuracy you can involve server end and send silent notifications from server which will give your application a 30 second window to determine user location and fire a local notification.

CoreLocation stops getting updates after idling

I have an app that collects lat/long coordinates ONLY using the GPS chip in an iPad (IE no wifi or cellular on ios8). It seems to work consistently unless the app is idled for about an hour (The app is still opened but the iPad locks.) Here is my code
I call [self.locman startUpdatingLocation]; in an IBAction upon pressing a UIButton that gets the coordinates and stores them to a text file in the documents directory.
// Delegate method from the CLLocationManagerDelegate protocol.
- (void)locationManager:(CLLocationManager *)manager
didUpdateLocations:(NSArray *)locations {
// If it's a relatively recent event, turn off updates to save power.
CLLocation* location = [locations lastObject];
NSDate* eventDate = location.timestamp;
NSTimeInterval howRecent = [eventDate timeIntervalSinceNow];
if (abs(howRecent) < 1) {
self.lat = [NSString stringWithFormat:#"%.8f",location.coordinate.latitude];
self.longString = [NSString stringWithFormat:#"%.8f",location.coordinate.longitude];
[self.locman stopUpdatingLocation];
}
}
Also if it doesn't get updates after a hour long hiatus, the app will subsequently get updates if the user presses the button again within an hour. So it seems to be a warming up issue.
To clarify. It seems to be a timing issue. For testing purposes I would collect coordinates....drive for 5 minutes, and collect coordinates. I could do this plenty of times with ~a 5 min interval in between stops. This would work perfectly, regardless of the screen turning blank or me pressing the 'sleep' button. The issue arises when I leave the ipad alone for around an hour (way longer than 5 minutes). Then the app will give me coordinates of 0.000000 and 0.0000000.
Here is the instantiation for my location manager.
self.locman = [[CLLocationManager alloc] init];
//self.locman.pausesLocationUpdatesAutomatically = NO;
self.locman.delegate = self;
self.locman.desiredAccuracy = kCLLocationAccuracyBest;
self.locman.distanceFilter = kCLDistanceFilterNone;
self.locman.desiredAccuracy = kCLLocationAccuracyHundredMeters;
You shouldn't stop updating the location for recent updates, let the framework handle the frequency. It's a good idea to check the time stamp to make sure you don't have old location data -- the location manager typically delivers previously cached location data immediately and then delivers more up-to-date location data as it becomes available.
Which iOS version is this? In iOS 8, you will need to call requestAlwaysAuthorization in order to receive location updates in the background.
Can you give more details on how you have set up your location manager?
It's possible that your app is being killed by the system after a certain time. This could happen if there is a memory leak.

When should I stop updating location manager?

I have an app that makes a call to get the user's location:
-(void)getLocation{
locationManager = [[CLLocationManager alloc] init];
locationManager.delegate = self;
locationManager.distanceFilter = kCLDistanceFilterNone;
locationManager.desiredAccuracy = kCLLocationAccuracyBest;
[locationManager startUpdatingLocation];
}
//SET USER LOCATION
-(void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations {
self.userLocation = [locations lastObject];
NSLog(#"location in IntroVC %f, %f", self.userLocation.coordinate.latitude, self.userLocation.coordinate.longitude);
}
My question is, because that NSLog keeps spitting out a new location infinitely, when should I stop calling the location? Well I guess its really up to my app's functionality, but doesnt this cause battery drain? If so, I should really look into the best way of stopping the updates.
Your Distance filter of the location manager is set to be kCLDistanceFilterNone. This causes the didUpdateLocations method to be called infinite time.
locationManager.distanceFilter = kCLDistanceFilterNone;
Change this line as
locationManager.distanceFilter = 10;
and try again. Change the value as needed.
So now the didUpdateLocation will not be called infinite times. :)
Hopefully this helps.
Depending on the nature of your app, you may well want to turn location services off when you go into the background or when the screen is locked. These notifications hooks are provided generally in your app delegate file (.m). Yes you are right, location services significantly drain battery and it a highly recommended practice for iOS apps using location services to use it cautiously.
Apple seems to have thought about this and has provided an API that notifies the app only if the user has moved "significantly" Apple the significant change location service. The definition of "moved significantly" varies on various aspects depending on WiFi availability, cell tower availability, GPS availability etc. Luckily all this is obfuscated within this API.
I call this method after updating the location in didupdateloactions, so when my app goes in background it remove location icon from top status bar.

Resources