How to get users current location on app launch - ios

I want to get users current location(lat,long) on the app launch only..i dont want to use delegate method for frequent location updates..I m not using maps just need current location on launch..how should i do this??
I am using the code below but its not working.
CLLocationManager *locationManager;
locationManager = [[CLLocationManager alloc] init];
locationManager.delegate=self;
locationManager.desiredAccuracy=kCLLocationAccuracyBest;
locationManager.distanceFilter=kCLDistanceFilterNone;
[locationManager startUpdatingLocation];
CLLocation *location;
location = [locationManager location];
CLLocationCoordinate2D coord;
coord.longitude = location.coordinate.longitude;
coord.latitude = location.coordinate.latitude;
NSLog(#"latitude %f longitude %f",coord.latitude,coord.longitude);
Output:-
latitude 0.000000 longitude 0.000000
please help..

better you use the delegate method to get user location and in didupdateLocation method stop it
I think this url may help you
iPhone SDK: Track users location using GPS
and in
-(void)locationManager:(CLLocationManager *)manager
didUpdateToLocation:(CLLocation *)newLocation
fromLocation:(CLLocation *)oldLocation{
CLLocationCoordinate2D here = newLocation.coordinate;
NSLog(#"%f %f ", here.latitude, here.longitude);
[locationManager stopUpdatingLocation];
}
and you done with it...

- (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation
{
// NSLog(#"didUpdateToLocation: %#", newLocation);
CLLocation *currentLocation = newLocation;
// Reverse Geocoding
// NSLog(#"Resolving the Address");
[geocoder reverseGeocodeLocation:currentLocation completionHandler:^(NSArray *placemarks, NSError *error) {
// NSLog(#"Found placemarks: %#, error: %#", placemarks, error);
if (error == nil && [placemarks count] > 0) {
placemark = [placemarks lastObject];
[locationManager stopUpdatingLocation];
} else {
NSLog(#"%#", error.debugDescription);
}
} ];
}

Use CLLocationManagerDelegate method
- (void)locationManager:(CLLocationManager *)manager
didUpdateToLocation:(CLLocation *)newLocation
fromLocation:(CLLocation *)oldLocation
{
[_locationManager stopUpdatingLocation];
NSLog(#"latitude %f longitude %f",newLocation.coordinate.latitude,,newLocation.coordinate.longitude);
}
Above method is deprecated in iOS6, use locationManager:didUpdateLocations: instead
- (void)locationManager:(CLLocationManager *)manager
didUpdateLocations:(NSArray *)locations

import <CoreLocation/CoreLocation.h>
delegate: CLLocationManagerDelegate
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
// System alert for Allowing current location of user.
// Location manager object creation.
locationManager = [[CLLocationManager alloc] init];`enter code here`
locationManager.delegate = self;
locationManager.distanceFilter = kCLDistanceFilterNone;
locationManager.desiredAccuracy = kCLLocationAccuracyBest;
[locationManager startUpdatingLocation];
}
// iOS >= 6.0.
- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations
{
[locationManager stopUpdatingLocation];
}
// iOS < 6.0
- (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation
{
[locationManager stopUpdatingLocation];
}

Related

Can't get Region Monitoring to function

After trying for a while using Apple's documentation, Stackoverflow, Google, I still can't get a simple UIAlertView to show up when I enter or exit a region I am monitoring.
self.locationManager = [[CLLocationManager alloc] init];
self.locationManager.distanceFilter = kCLDistanceFilterNone;
self.locationManager.desiredAccuracy = kCLLocationAccuracyBest;
self.locationManager.delegate = self;
[locationManager requestAlwaysAuthorization];
for (CLRegion *monitored in [self.locationManager monitoredRegions])
[locationManager stopMonitoringForRegion:monitored];
CLLocationCoordinate2D coord;
coord.latitude = 31.521603;
coord.longitude = 33.01190;
CLCircularRegion *region = [[CLCircularRegion alloc]initWithCenter:coord radius:20 identifier:#"work"];
- (void)locationManager:(CLLocationManager *)manager didEnterRegion:(CLRegion *)region
{
[self showMessage:[NSString stringWithFormat:#"EnterRegion: %#",region.identifier] andMessage:#"Welcome Home" andButton:#"Ok"];
}
- (void)locationManager:(CLLocationManager *)manager didExitRegion:(CLRegion *)region
{
[self showMessage:[NSString stringWithFormat:#"ExitRegion: %#",region.identifier] andMessage:#"Bye Bye" andButton:#"Ok"];
}
-(void)locationManager:(CLLocationManager *)manager didStartMonitoringForRegion:(CLRegion *)region {
NSLog(#"Now monitoring for %#", region.identifier);
}
- (void)locationManager:(CLLocationManager *)manager monitoringDidFailForRegion:(CLRegion *)region withError:(NSError *)error{
[self showMessage:#"msg" andMessage:[NSString stringWithFormat:#"Region Failed:%#",region.identifier] andButton:#"ok"];
}
- (void)locationManager:(CLLocationManager *)manager
didDetermineState:(CLRegionState)state forRegion:(CLRegion *)region
{
[self showMessage:[NSString stringWithFormat:#"Did Determine State: %#. state:%#",region.identifier, (state == CLRegionStateUnknown) ? #"Unknown" : (state == CLRegionStateInside) ? #"INSIDE" : #"OUTSIDE"] andMessage:#"Determined" andButton:#"Ok"];
}
- (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation{ }
showMessage is just a UIAlertView popping to the user.
sometimes I get monitoringDidFailForRegion when I set up the region sometimes I don't.
I was thinking if I should mark my app as using "Background Modes" for Location Updates, but this has not changed a thing. Seems like it should work, but I can never get didEnterRegion nor didExitRegion to be called.
I should point out that I updated the info.plist with the required keys:
<key>NSLocationAlwaysUsageDescription</key>
<string>Location is required for geofence</string>
Background app refresh is set to On, locations enabled. Testing outside, physically, I can't get the functions to be called.
What is it that can be wrong here? is 20 meters too short to define a region?
Could it be that region monitoring is not working for an app that is on the foreground? silencing the callbacks?

CoreLocation iOS9 storing Coordinates

I recently asked this question, not knowing of the changes made to CL in iOS 9. I am trying to store the user's current location and I have changed my code to reflect the new delegate methods in iOS 9, but didUpdateLocations is still never reached.
Here is the link to my original question: Latitude & Longitude Not Retrieved
And my updated code:
viewWillAppear
- (void)viewWillAppear:(BOOL)animated{
manager = [[CLLocationManager alloc] init];
manager.delegate = self;
if ([manager respondsToSelector:#selector(requestWhenInUseAuthorization)]) {
[manager requestWhenInUseAuthorization];
}
[manager startUpdatingLocation];
}
didUpdateLocations
- (void)locationManager:(CLLocationManager *)manager
didUpdateLocations:(NSArray<CLLocation *> *)locations{
NSLog(#"Location: %#", locations);
CLLocation *currentLocation = locations.lastObject;
if (currentLocation != nil) {
float latitude = currentLocation.coordinate.latitude;
float longitude = currentLocation.coordinate.longitude;
NSLog(#"dLongitude : %f", longitude);
NSLog(#"dLatitude : %f", latitude);
}
else{ NSLog(#"ERROR");
}
}
check for
authorizationStatus and startUpdatingLocation
and
- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations
- (void)locationManager:(CLLocationManager *)manager didChangeAuthorizationStatus:(CLAuthorizationStatus)status
you can also go to settings ->privacy -> location services (turn on) -> select ur app and select while using.

Testing a fake current location on iOS Simulater is not working

I have been trying to fake my location in the iOS simulator but the methods I have been reading about are not working. I have used the debugger to set my fake location, and have made a custom location in Debug->Location->Custom Location, yet I still log 0.000 0.000 for lat and long.
I'm using this code to find current location.
- (IBAction)currentLocationButtonPressed:(UIButton *)sender
{
//Search for pubs and bars in current location.
//Push to tableViewController
NSLog(#"current location Pressed.");
locationManager.distanceFilter = kCLDistanceFilterNone; // whenever we move
locationManager.desiredAccuracy = kCLLocationAccuracyBest; // Best accuracy
[locationManager startUpdatingLocation];
NSLog(#"%#",[self deviceLocation]);
}
- (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation
{
NSLog(#"didUpdateToLocation: %#", newLocation);
CLLocation *currentLocation = newLocation;
if (currentLocation != nil) {
NSLog(#"Latitude: %f Longitude: %f", currentLocation.coordinate.latitude, currentLocation.coordinate.longitude);
}
}
- (NSString *)deviceLocation {
return [NSString stringWithFormat:#"latitude: %f longitude: %f", locationManager.location.coordinate.latitude, locationManager.location.coordinate.longitude];
}
The delegate is set and I am requesting authorization.
- (void)viewDidLoad {
[super viewDidLoad];
searchLocationTextField.delegate = self;
locationManager.delegate = self;
locationManager = [[CLLocationManager alloc]init];
[locationManager requestWhenInUseAuthorization]; // For foreground access
[locationManager requestAlwaysAuthorization]; // For background access
}
Set locationManager delegate to after allocating it.
locationManager = [[CLLocationManager alloc]init];
locationManager.delegate = self;
locationManager:didUpdateToLocation:fromLocation: delegate method is deprecated, use locationManager:didUpdateLocations: instead.
-(void) locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations
{
CLLocation *currentLocation = [locations lastObject];
NSLog(#"Latitude: %f Longitude: %f", currentLocation.coordinate.latitude, currentLocation.coordinate.longitude);
}

Iphone device getting the user location define in xcode

I am using CLLocationManger to get device current location. All is going well on simulation. I check the "Allow Location Simulation" and set Sydney, Australia as default location. I got the lat and long of Sydney on simulator that is fine
My problem is that when i try on device I still get the Sydney location however my device current location is India.
My device get the location what ever I set in Xcode.
Here is my code:
locationManager = [[CLLocationManager alloc] init];
locationManager.delegate = self;
locationManager.distanceFilter = 1;
locationManager.desiredAccuracy = kCLLocationAccuracyBest;
[locationManager startUpdatingLocation];
#pragma mark delegate method which tell the current location
- (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation
{
latitudeCurrentLocation = [NSString stringWithFormat:#"%f",newLocation.coordinate.latitude];
longitudeCurrentLocation= [NSString stringWithFormat:#"%f",newLocation.coordinate.longitude];
[locationManager stopUpdatingLocation];
locationManager=nil;
NSLog(#"OldLocation %f %f", oldLocation.coordinate.latitude, oldLocation.coordinate.longitude);
}
-(void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error
{
}
Please suggest what should I should do.
Use this delegate method and check your location address
- (void)locationManager:(CLLocationManager *)manager
didUpdateLocations:(NSArray *)locations
Here is sample code :
-(void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations
{
CLGeocoder *geocoder = [[CLGeocoder alloc] init];
[geocoder reverseGeocodeLocation:_locationManager.location
completionHandler:^(NSArray *placemarks, NSError *error) {
NSLog(#"reverseGeocodeLocation:completionHandler: Completion Handler called!");
if (error){
NSLog(#"Geocode failed with error: %#", error);
return;
}
NSLog(#"placemarks=%#",placemarks);
CLPlacemark *placemark = [placemarks objectAtIndex:0];
NSLog(#"placemark.ISOcountryCode =%#",placemark.ISOcountryCode);
NSLog(#"placemark.country =%#",placemark.country);
NSLog(#"placemark.postalCode =%#",placemark.postalCode);
NSLog(#"placemark.administrativeArea =%#",placemark.administrativeArea);
NSLog(#"placemark.locality =%#",placemark.locality);
NSLog(#"placemark.subLocality =%#",placemark.subLocality);
NSLog(#"placemark.subThoroughfare =%#",placemark.subThoroughfare);
NSLog(#"stringlocation:%#",_cityString);
}];
_userLocation = [locations lastObject]; // This will give you co-ordinates
[_locationManager stopUpdatingLocation];
}
When you run this in your device select don't simulate location

Location Manager is not updating location

I have the following code:
- (void) viewWillAppear {
[self startSignificantChangeUpdates];
}
- (void)startSignificantChangeUpdates
{
if ([CLLocationManager locationServicesEnabled])
{
NSLog(#"start significant changes");
if (nil == locationManager)
locationManager = [[CLLocationManager alloc] init];
locationManager.delegate = self;
[locationManager startMonitoringSignificantLocationChanges];
}
}
problem is that the location manage is not calling its delegate function
- (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation {
What can I do?
In your .h file:
#import <CoreLocation/CoreLocation.h>
#interface ViewController : UIViewController <CLLocationManagerDelegate>
In your .m file:
#implementation ViewController {
// This is a private variable, used within this file only
CLLocationManager *locationManager;
}
-(void)viewDidLoad {
locationManager = [[CLLocationManager alloc] init];
}
-(void)viewWillAppear {
// If the delegate is still not being set, try putting this code into viewDidAppear
locationManager.delegate = self;
locationManager.desiredAccuracy = kCLLocationAccuracyBest;
[locationManager startUpdatingLocation];
}
-(void)locationManger:(CLLocationManager *)manager didFailWithError:(NSError *)error {
NSLog(#"didFailWithError: %#", error);
}
-(void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations {
NSLog(#"didUpdateToLocation: %#", [locations lastObject]);
CLLocation *currentLocation = [locations lastObject];
[locationManager stopUpdatingLocation];
}
For more information about getting the user's location, look at this guide, which I used to implement location into an app of mine: http://www.appcoda.com/how-to-get-current-location-iphone-user/
How are you testing this? If you are running this in the simulator, you can go to Debug->Location->Freeway Drive. You can put a break point in locationManager:didUpdateToLocation method or even put a log statement to log the current location coordinates. You should see it work.
Please replace this line
[locationManager startMonitoringSignificantLocationChanges];
with this code
[locationController.locationManager startUpdatingLocation];
and then check
- (void)locationManager:(CLLocationManager *)manager
didUpdateToLocation:(CLLocation *)newLocation
fromLocation:(CLLocation *)oldLocation
{
}

Resources