Start GPS Application As a Service - iphone

(BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
// Override point for customization after application launch.
locmanager = [[CLLocationManager alloc] init];
[locmanager setDelegate:self];
[locmanager setDesiredAccuracy:kCLLocationAccuracyHundredMeters];
[locmanager setDistanceFilter:10];
[locmanager startUpdatingLocation];
[window makeKeyAndVisible];
return YES;
}
- (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation
{
CLLocationCoordinate2D loc = [newLocation coordinate];
latitude = [NSString stringWithFormat: #"%f", loc.latitude];
longitude= [NSString stringWithFormat: #"%f", loc.longitude];
//Call to the web service for sending data
}
Will it be possible to start this application automatically when the phone starts.I don't want users to start this.

No, the only way for your application to start is for a user to start it, either by tapping on it on the home screen, or by opening it through a push notification.
CoreLocation runs in the background as part of iOS, but your app can only access that data when it is open. If it is running in multitasking mode, I imagine that you'd be able to access location data through a background task.
Note that a "Location" indicator will appear in the status bar on the right whenever you use Core Location. This is done for privacy reasons.

No. Not unless it's jailbroken.

Related

How to get current Location info using wifi or cellular without using GPS in ios

Currently I am working in a project , its requirement is to get the current location information specially latitude and longitude value in every 200m interval using wifi network or Cellular network without using gps as it is consuming more battery life.
Is this possible in ios latest version .
If any one having any idea ,please share with me ,
Thank you.
Have a look in to CLLocationManager, That will be able to tell you where the user is located.
.h
#import <CoreLocation/CoreLocation.h>
#property(nonatomic,retain) CLLocationManager *locationManager;
.m
- (void)viewDidLoad
{
locationManager = [[CLLocationManager alloc] init];
locationManager.delegate = self;
//let the user know the purpose
locationManager.purpose = #"Enable location services";
locationManager.distanceFilter = kCLDistanceFilterNone;
locationManager.desiredAccuracy = kCLLocationAccuracyHundredMeters; // 100 m
NSLog(#"User latitude: %f",locationManager.location.coordinate.latitude);
NSLog(#"User longitude: %f",locationManager.location.coordinate.longitude);
[locationManager startUpdatingLocation];
}
It only way to get your location info in every 200m that is CLLocationManager's startUpdatingLocation. But it is comsuming a lot of battery.
But there is a little different way to get your location when it is changed.
CLLocationManager's startMonitoringSignificantLocationChanges.
Here is a Link
The location manager protocol reference
https://developer.apple.com/library/mac/#documentation/CoreLocation/Reference/CLLocationManagerDelegate_Protocol/CLLocationManagerDelegate/CLLocationManagerDelegate.html
1.In Appdelegate
#import <CoreLocation/CoreLocation.h>
In #interface file
CLLocationManager *locationManager;
#property (nonatomic, retain) CLLocationManager *locationManager;
and add protocol CLLocationManagerDelegate protocol.
2.Impliment these functions in .m.
#synthesize locationManager;
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
self.locationManager = [[[CLLocationManager alloc] init] autorelease];
self.locationManager.delegate = self;
self.locationManager.desiredAccuracy = kCLLocationAccuracyBest;
self.locationManager.distanceFilter = 1.0;
[self.locationManager startUpdatingLocation];
}
- (void)locationManager:(CLLocationManager *)manager didEnterRegion:(CLRegion *)region
{
// Show an alert or otherwise notify the user
}
- (void)locationManager:(CLLocationManager *)manager didExitRegion:(CLRegion *)region
{
}
- (void)locationManager:(CLLocationManager *)manager monitoringDidFailForRegion:(CLRegion *)region withError:(NSError *)error
{
}
Note:If you want to debug first set current location in simulator
At Debug--->Location--->Custom Location.
its requirement is to get the current location information specially latitude and longitude value in every 200m interval using wifi network or Cellular network without using gps as it is consuming more battery life
The documentation for CLLocationManager has this to say about distance and the GPS hardware:
... setting the desired accuracy for location events to one kilometer gives the location manager the flexibility to turn off GPS hardware and rely solely on the WiFi or cell radios.
For less than 200 meters you'll probably need to roll-your-own solution here.
- (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation {
[locationManager stopUpdatingLocation];
[locationManager stopMonitoringSignificantLocationChanges];
[self performSelector:#selector(stopUpadateLocation)];
CLLocation *location = [locationManager location];
CLLocationCoordinate2D coord;
coord=[location coordinate];
NSLog(#"coord %f %f", coord.latitude, coord.longitude);
NSString *urlString = [NSString stringWithFormat:#"http://maps.google.com/maps/geo?q=%f,%f&output=json", newLocation.coordinate.latitude, newLocation.coordinate.longitude];
NSURL *url = [NSURL URLWithString:urlString];
NSString *locationString = [NSString stringWithContentsOfURL:url encoding:NSUTF8StringEncoding error:nil];
NSDictionary *dic=[locationString JSONValue];
NSLog(#"locationString:%#",locationString );
[strAddr setString:[AppUtility removeNull:[NSString stringWithFormat:#"%#",[[[dic valueForKey:#"Placemark"] objectAtIndex:0] valueForKey:#"address"]]]];
[txtNear setText:strAddr];
}
- (void)startUpdateLocation{
[locationManager startUpdatingLocation];
}
- (void)stopUpadateLocation{
[locationManager stopUpdatingLocation];
[locationManager stopMonitoringSignificantLocationChanges];
}
You have to use the Core Location method startMonitoringSignificantLocationChanges which uses only the wifi or cellular networks!

Sending location to server with CLLocationManager when iphone is in background

i'm having trouble sending my position when the application lies in the background. I'm using CLLocationManager and startMonitoringSignificantLocationChanges. The posision didUpdateToLocation delegate method is performed once, but not more. I've tried to walk around but no new locations is sent to the server.
I have set the "Required background modes" -> "App registers for location updates" in the info.plist file.
Anyone got an idea on what might be wrong?
Code from where the tracking is started:
CLLocationManager *locationManager = [[CLLocationManager alloc] init];
locationManager.delegate = appDelegate;
[appDelegate setLocationManager:locationManager withDistanceFilter:kCLDistanceFilterNone];
[appDelegate.theLocationManager startMonitoringSignificantLocationChanges];
Code (from CLLocationManagerDelegate):
- (void)setLocationManager:(CLLocationManager*)locationManager withDistanceFilter:(CLLocationDistance)distanceFilter {
// create a new manager and start checking for sig changes
self.theLocationManager.delegate = nil;
[theLocationManager release];
self.theLocationManager = locationManager;
self.theLocationManager.delegate = self;
self.theLocationManager.distanceFilter = distanceFilter;
}
- (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation {
NSDate *newLocationTimestamp = newLocation.timestamp;
NSDate *oldLocationTimestamp = oldLocation.timestamp;
int locationUpdateInterval = 15;//15 sec
if (!([newLocationTimestamp timeIntervalSinceDate:oldLocationTimestamp] < locationUpdateInterval)) {
//NSLog(#"New Location: %#", newLocation);
[self updateToLocation:newLocation];
}
}
- (void)updateToLocation:(CLLocation *)newLocation {
NSLog(#"update location!!");
NSString *latitude = [NSString stringWithFormat:#"%f", [newLocation coordinate].latitude];
NSString *longitude = [NSString stringWithFormat:#"%f", [newLocation coordinate].longitude];
[currentUser updatePositionWithLongitude:longitude andLatitude:latitude];
}
Like Bill Brasky said, the accuracy to which you have set your location manager is likely not registering the distance that you have walked. Try setting your location manager accuracy much higher, just to see if works, then dial it back down to a happy medium between accuracy and battery efficiency. Just for testing, take it all the way up:
[appDelegate.theLocationManager setDesiredAccuracy:kCLLocationAccuracyBestForNavigation];
Then instead of:
[appDelegate.theLocationManager startMonitoringSignificantLocationChanges];
try:
[appDelegate.theLocationManager startUpdatingLocation];
The -startMonitoringForSignificantLocationChanges is directly tied to cell tower connectivity. You may need to travel miles to get connection to a new tower and trigger a location change event. I know that the region monitoring is a bit more accurate as it uses updates of location from Wifi, cell tower, and even other apps that inquire on location. You will need to figure out how accurate and how often you need your app to be. You may need to actively monitor location in the background (which would be a battery killer for sure). Hope this helps.

CLLocation manager keep getting same latitude and longitude when clicking button?

This is my first question in this site.
I have this serious problem.... I'll explain this from the beginning…
in my app i need to get the current location of the user when the user click on the button in the application.. but the problem is when is click on the button its not updating to the current location its getting the previous location. But when i reset the location warnings in the iphone app its get the correct location.
Here is the code steps i did for this application to get the current location of the user...
First I import to the application ...
then i am using global files to keep data of the application because i need to access them through the application.
so what I did in the globle.m and .h file is ...
CLLocationManager* locationManager;
#synthesize locationManager
+ (Globals*)sharedGlobals {
#synchronized(self) {
if(_sharedGlobals == nil) {
_sharedGlobals = [[super allocWithZone:NULL] init];
_sharedGlobals.locationManager = [[CLLocationManager alloc]init];
[_sharedGlobals.locationManager setDesiredAccuracy:kCLLocationAccuracyBest];
}
}
return _sharedGlobals;
}
Then in my other view controller I put the CLLocationManagerDelegate and in the .m file
-(IBAction) didTapSearchbtn{
if (![CLLocationManager locationServicesEnabled]) {
}else {
[[Globals sharedGlobals].geoLocations removeAllObjects];
search.text = nil;
[Globals sharedGlobals].fromTextField = NO;
[[Globals sharedGlobals].locationManager setDelegate:self];
[[Globals sharedGlobals].locationManager startUpdatingLocation];
}
}
- (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation {
if (newLocation.horizontalAccuracy < 0) return;
[[Globals sharedGlobals].locationManager setDelegate:nil];
[[Globals sharedGlobals].locationManager stopUpdatingLocation];
[[Globals sharedGlobals].geoLocations setObject:[[NSString alloc] initWithFormat:#"%f", newLocation.coordinate.latitude] forKey:#"geolat"];
[[Globals sharedGlobals].geoLocations setObject:[[NSString alloc] initWithFormat:#"%f", newLocation.coordinate.longitude] forKey:#"geolong"];
[self retriveDataFromInternet];
[[Globals sharedGlobals].locationManager release];
}
- (void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error {
//GPS error
[[Globals sharedGlobals].locationManager setDelegate:nil];
[[Globals sharedGlobals].locationManager stopUpdatingLocation];
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:NSLocalizedString(#"YumTable!", nil) message:NSLocalizedString(#"Enable Your GPS settings to get your current location", nil) delegate:nil cancelButtonTitle:NSLocalizedString(#"Ok", nil) otherButtonTitles:nil];
[alert show];
[alert release];
[[Globals sharedGlobals].locationManager release];
}
i put the label to my view controller and went different places to take latitudes and longitudes .. but always it getting same latitude and longitude ... but when I reset the location warnings and run the app again it took the correct latitude and longitude ... so if i need to take current location always i have to reset it. But what i need is to get current location every time when i click the search button...
Can any one can say whats wrong in this code and can any one help me ....
And Also very very sorry about my bad english ... :)
The LocationManager will return the previos location because it tries to be as fast as possible and it thinks that this location might be good enough. I usually check the timestamp on the new location to ensure that it is a fresh one. If it is to old I don't stop the manager and wait for the next one.
I would suggest that you look at the sample code provided by Apple, https://developer.apple.com/library/ios/#samplecode/LocateMe/Introduction/Intro.html#//apple_ref/doc/uid/DTS40007801
This code is copied from the example:
- (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation {
// test the age of the location measurement to determine if the measurement is cached
// in most cases you will not want to rely on cached measurements
NSTimeInterval locationAge = -[newLocation.timestamp timeIntervalSinceNow];
if (locationAge > 5.0) return;
}
I missed Typed my code ... after I figur that out my application start to work perfectly ... Thank you guys for your great help..
[_sharedGlobals.locationManager setDesiredAccuracy:kCLLocationAccuracyBest];
instead of that I used
[_sharedGlobals.locationManager setDesiredAccuracy:kCLLocationAccuracyBestforNavigation];

Returning a users lat lng as a string iPhone

Is there a way to return the users location as a string from a model?
I have a model thats job is to download same JSON data from a web service. When sending in my request I need to add ?lat=LAT_HERE&lng=LNG_HERE to the end of the string.
I have seen tons of examples using the map or constantly updating a label. But I cant find out how to explicitly return the lat and lng values.
Im only 2 days into iPhone dev so go easy on me :)
You need to leverage Core Location, specifically CLLocationManager. Apple doesn't provide any CL programming guide, so just look at one of the samples like LocateMe to see how to do it.
You need to use CLLocationManager like this:
- (void)viewDidLoad
{
// this creates the CCLocationManager that will find your current location
CLLocationManager *locationManager = [[[CLLocationManager alloc] init] autorelease];
locationManager.delegate = self;
locationManager.desiredAccuracy = kCLLocationAccuracyNearestTenMeters;
[locationManager startUpdatingLocation];
}
// this delegate is called when the app successfully finds your current location
- (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation
{
// retrieve lat and lng in a string from newLocation.coordinate
NSString *lat = [NSString stringWithFormat:#"%d", newLocation.coordinate.latitude];
NSString *lng = [NSString stringWithFormat:#"%d", newLocation.coordinate.longitude];
}
// this delegate method is called if an error occurs in locating your current location
- (void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error
{
NSLog(#"locationManager:%# didFailWithError:%#", manager, error);
}

CLLocationManger gives old location. How to get the new location?

I am using the CLLocationManger to update the current location. Though its giving me the location but the location I am getting is of much older timestamp. I am facing the problem in, how to force the locationcontroller to update the fresh location not the cached location.
Currently I am using this tutorial......
http://www.mobileorchard.com/hello-there-a-corelocation-tutorial/
Anybody know how to update location at current timestamp not the cached one?
Are you running your project on simulator or on iPhone? If you are running project on simulator then
-(void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation
will be called only once.
If you are testing on device then it should be called everytime your location is changed.
Make sure you have set the location manager property,
locationManager.delegate=self;
[locationManager startUpdatingLocation];
Hope that helps...
you can use this methods
- (IBAction)update {
locmanager = [[CLLocationManager alloc] init];
[locmanager setDelegate:self];
[locmanager setDesiredAccuracy:kCLLocationAccuracyBest];
NSLog(#"*********this is location update method of login view controller");
[locmanager startUpdatingLocation];
}
-(void)awakeFromNib {
[self update];
}
- (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation
{
if (wasFound) return;
wasFound = YES;
CLLocationCoordinate2D loc = [newLocation coordinate];
lat2 = [[NSString stringWithFormat: #"%f", loc.latitude]retain];
logg2= [[NSString stringWithFormat: #"%f", loc.longitude]retain];
NSLog(#"latitude is %#",lat2);
NSLog(#"longitude is %#",logg2);
}
call the update method using perform selector in viewdidload method.Here lat2 and logg2 are string values.
if problem can't be solved then type how to find current location in google.you will get many examples source code with explanation
The best you can do is throw out locations that are too old by whatever standard you decide to set for your app. Restarting the location manager is supposed to tell the system you want a new location, but usually the first location you get back may be whatever it had last. Checking the timestamp may be all you can do, but be prepared for the possibility that you may never get a newer location. I've seen in my experience that if the device hasn't moved, it never bothers to update the system with a new location if it detects that the current location is good enough.