I have methods in viewDidLoad, and it seems like the order of methods getting called is weird.
- (void)viewDidLoad
{
[super viewDidLoad];
// Get Location
self.locationManager = [[CLLocationManager alloc] init];
self.geocoder = [[CLGeocoder alloc] init];
self.locationManager.delegate = self;
self.locationManager.desiredAccuracy = kCLLocationAccuracyBest;
if([self.locationManager respondsToSelector:#selector(requestWhenInUseAuthorization)])
{
[self.locationManager requestWhenInUseAuthorization];
}
[self.locationManager startUpdatingLocation];
// Retrieve Data
[self retrieveData];
}
After viewDidLoad is called, it calls the retrieveData method before locationManager.
Shouldn't the locationManager be called before retrieveData because of the order?
I am new in Objective C, thank you for your help in advance.
as per your need call your method in inside the delegate methods, so remove the [self retrieveData]; from ViewDidLoad and add into inside the didFailWithError or didUpdateLocations methods.
- (void)viewDidLoad
{
[super viewDidLoad];
// Get Location
self.locationManager = [[CLLocationManager alloc] init];
self.geocoder = [[CLGeocoder alloc] init];
self.locationManager.delegate = self;
self.locationManager.desiredAccuracy = kCLLocationAccuracyBest;
if([self.locationManager respondsToSelector:#selector(requestWhenInUseAuthorization)])
{
[self.locationManager requestWhenInUseAuthorization];
}
[self.locationManager startUpdatingLocation];
}
- (void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error
{
UIAlertView *errorAlert = [[UIAlertView alloc]
initWithTitle:#"Error"
message:#"Failed to Get Your Location"
delegate:nil
cancelButtonTitle:#"OK"
otherButtonTitles:nil];
[errorAlert show];
// call here
[self retrieveData];
}
- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations
{
// set or stop your location update
manager = nil;
[self.locationManager stopUpdatingLocation];
[manager stopUpdatingLocation];
CLLocation *newLocation = locations[[locations count] -1];
CLLocation *currentLocation = newLocation;
NSString *longitude = [NSString stringWithFormat:#"%.8f", currentLocation.coordinate.longitude];
NSString *latitude = [NSString stringWithFormat:#"%.8f", currentLocation.coordinate.latitude];
if (currentLocation != nil) {
NSLog(#"latitude: %#", latitude);
NSLog(#"longitude: #"%#", longitude);
}else {
UIAlertView *errorAlert = [[UIAlertView alloc]
initWithTitle:#"Error" message:#"Failed to Get Your Location"
delegate:nil
cancelButtonTitle:#"OK"
otherButtonTitles:nil];
[errorAlert show];
}
// call here
[self retrieveData];
}
Note
objective -C is the interpreter , it execute the every in step by step , so or may be your [self retrieveData]; is called in main thread, that is the reason it execute in prior.
Related
I have made one demo for getting Current Location.
I have used .GPX file for my current Location.
I have used Delegates method of CLLocation Method.
I have Also use Key "Privacy - Location When In Use Usage Description" in my plist file.
I know this question already asked so many time but could not able to get result.
code is
#import "ViewController.h"
#import <CoreLocation/CoreLocation.h>
#import <MapKit/MapKit.h>
#interface ViewController ()<CLLocationManagerDelegate,MKMapViewDelegate>
#property (nonatomic,assign)CLLocationCoordinate2D cordinateLocation;
#property (nonatomic,strong)MKPointAnnotation *point;
#property (nonatomic,weak)IBOutlet MKMapView *mapView;
#end
#implementation ViewController
CLLocationManager *locationManager;
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
locationManager = [[CLLocationManager alloc]init];
locationManager.delegate = self;
self.mapView.delegate = self;
[self updateCurrentLocation];
}
- (void)updateCurrentLocation {
locationManager = [[CLLocationManager alloc] init];
locationManager.delegate = self;
if ([locationManager respondsToSelector:#selector(requestWhenInUseAuthorization)]) {
[locationManager requestWhenInUseAuthorization];
}
[locationManager startUpdatingLocation];
}
//-(void)getCurrentLocation
//{
// [locationManager requestWhenInUseAuthorization];
// locationManager.desiredAccuracy = kCLLocationAccuracyBest;
// [locationManager startUpdatingHeading];
// [locationManager startUpdatingLocation];
//
//}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
- (void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error
{
NSLog(#"didFailWithError: %#", error);
UIAlertController *errorAlert =[UIAlertController alertControllerWithTitle:#"Error" message:#"error reported" preferredStyle:UIAlertControllerStyleAlert];
UIAlertAction *alertStyle = [UIAlertAction actionWithTitle:#"OK" style:UIAlertActionStyleDefault handler:nil];
[errorAlert addAction:alertStyle];
}
- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray<CLLocation *> *)locations
{
CLLocation *updatedLocation = [locations lastObject];
if(updatedLocation != nil)
{
self.cordinateLocation=CLLocationCoordinate2DMake(updatedLocation.coordinate.latitude, updatedLocation.coordinate.longitude);
[manager stopUpdatingLocation];
[self setCurrentLocationFocus];
}
else{
NSLog(#"Can't access desire location");
}
}
-(void)setCurrentLocationFocus{
MKCoordinateRegion region;
region.center = self.cordinateLocation;
//Adjust span as you like
MKCoordinateSpan span;
span.latitudeDelta = 1;
span.longitudeDelta = 1;
region.span = span;
[self.mapView setRegion:region animated:YES];
///Drop the pin on Current Locatio ////
self.point = [[MKPointAnnotation alloc] init];
self.point.coordinate = self.cordinateLocation;
self.point.title = #"FlockStation";
self.point.subtitle = #"It Department";
[self.mapView addAnnotation:self.point];
//set a new camera angle
MKMapCamera *newCamera=[[MKMapCamera alloc] init];
[newCamera setCenterCoordinate:self.cordinateLocation];
[newCamera setPitch:60.0]; ///For zooming purpose///
[newCamera setHeading:90]; ///For Compass Purpose ///
[newCamera setAltitude:100.0]; ///On which height you want to see your map ///
[self.mapView setCamera:newCamera animated:YES];
}
- (void)mapView:(MKMapView *)mapView didSelectAnnotationView:(MKAnnotationView *)view
{
UIStoryboard *mainStoryBoard = [UIStoryboard storyboardWithName:#"Main" bundle:nil];
UIViewController *viewController = [mainStoryBoard instantiateViewControllerWithIdentifier:#"NewViewController"];
[self presentViewController:viewController animated:YES completion:nil];
}
- (void)locationManager:(CLLocationManager *)manager didUpdateHeading:(CLHeading *)newHeading
{
// self.updatedHeading.text = [NSString stringWithFormat:#"%f",newHeading.magneticHeading];
}
Help Me guys not able to get location.Because delegates method is not calling.
Every Time it called this method.
- (void)locationManager:(CLLocationManager *)manager didFailWithError:`(NSError *)error
You need to check permission of location. then after you can call the delegate methods.
- (void)viewDidLoad {
[super viewDidLoad];
locationManager=[[CLLocationManager alloc] init];
locationManager.delegate = self;
locationManager.distanceFilter = kCLDistanceFilterNone;
locationManager.desiredAccuracy = kCLLocationAccuracyBest;
[locationManager startUpdatingLocation];
if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 8.0)
{
[locationManager requestWhenInUseAuthorization];
}
if ([CLLocationManager locationServicesEnabled]){
NSLog(#"Location Services Enabled");
if ([CLLocationManager authorizationStatus]==kCLAuthorizationStatusDenied){
alert = [[UIAlertView alloc] initWithTitle:#"Permission Denied"
message:#"To re-enable, please go to Settings and turn on Location Service for this app."
delegate:nil
cancelButtonTitle:#"OK"
otherButtonTitles:nil];
[alert show];
}
}
}
- (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation
{
CLLocation *currentLocation = newLocation;
txtlocations.text = [NSString stringWithFormat:#"%f & %f",currentLocation.coordinate.latitude, currentLocation.coordinate.longitude];
}
Tried with your code with little changes and its working fine.
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
[self updateCurrentLocation];
}
- (void)updateCurrentLocation {
if([CLLocationManager locationServicesEnabled] &&
[CLLocationManager authorizationStatus] != kCLAuthorizationStatusDenied) {
locationManager = [[CLLocationManager alloc] init];
locationManager.delegate=self;
locationManager.desiredAccuracy=kCLLocationAccuracyBest;
locationManager.distanceFilter=kCLDistanceFilterNone;
[locationManager requestWhenInUseAuthorization];
[locationManager startMonitoringSignificantLocationChanges];
[locationManager startUpdatingLocation];
// show the map
} else {
// show error
}
}
I have this code in my class ViewController:
CLLocationManager *locationManager;
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
locationManager = [[CLLocationManager alloc] init];
[locationManager requestWhenInUseAuthorization];
}
- (IBAction)getCurrentLocation:(id)sender {
locationManager.delegate = self;
locationManager.desiredAccuracy = kCLLocationAccuracyBest;
[locationManager startUpdatingLocation];
}
#pragma mark - CLLocationManagerDelegate
-(void) locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error {
NSLog(#"Did finish with error - %#", error);
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Error" message:#"Failed to get your location" delegate:nil cancelButtonTitle:#"OK" otherButtonTitles:nil, nil];
[alert show];
}
- (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation {
NSLog(#"did Update Location - %#", newLocation);
CLLocation *currentLocation = newLocation;
if(currentLocation != nil) {
_longitudeLabel.text = [NSString stringWithFormat:#"%.8f", currentLocation.coordinate.longitude];
_latitudeLabel.text = [NSString stringWithFormat:#"%.8f", currentLocation.coordinate.latitude];
}
}
But I am not getting the location or the popup for allowing access.
I am using the Core Location framework.
On button click I am printing latitude, longitude and address in labels.
I am testing this on the simulator.
Sometimes Simulator wont work with location enabled services use Apple Device for perfect testing.
Add the following keys inside your info.plist file to get allow access popup.
or add them as updating info.plist file source code.
<key>NSLocationAlwaysUsageDescription</key>
<string>message for location uses</string>
<key>NSLocationWhenInUseUsageDescription</key>
<string>message for location uses</string>
Try this code in viewDidLoad...
//---- For getting current gps location
locationManager = [CLLocationManager new];
locationManager.delegate = self;
if ([locationManager respondsToSelector:#selector(requestWhenInUseAuthorization)]) {
[locationManager requestWhenInUseAuthorization];
}
locationManager.distanceFilter = kCLDistanceFilterNone;
locationManager.desiredAccuracy = kCLLocationAccuracyBest;
[locationManager startUpdatingLocation];
//------
You also have to add a string for the NSLocationAlwaysUsageDescription or NSLocationWhenInUseUsageDescription keys to the app's Info.plist.
locationManager =[[CLLocationManager alloc] init];
[locationManager requestWhenInUseAuthorization];
locationManager.delegate=self;
locationManager.desiredAccuracy=kCLLocationAccuracyBest;
[locationManager startUpdatingLocation];
you can add in your plist:
<key>NSLocationAlwaysUsageDescription</key>
<key>NSLocationWhenInUseUsageDescription</key>
I know there is a lot of questions related to that,But I cant able to link with my Issue. In my app,I am fetching the Nearby Restaurant,Initially,If user clicks on 'Nearby' button I fetch the lat,long,placemark details,Using this code below.
-(void)setUpUserLocation
{
BOOL locationAllowed = [CLLocationManager locationServicesEnabled];
if (locationAllowed==NO)
{
UIAlertView *alertView = [[UIAlertView alloc]initWithTitle:#"No authorization"
message:#"Please, enable access to your location"
delegate:self cancelButtonTitle:#"Cancel"
otherButtonTitles:#"Open Settings", nil];
[alertView show];
}
else
{
locationManager = [[CLLocationManager alloc] init];
locationManager.delegate = self;
if ([locationManager respondsToSelector:#selector(requestWhenInUseAuthorization)]) {
[locationManager requestWhenInUseAuthorization];
}
}
[locationManager startUpdatingLocation];
}
-(void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations
{
CLLocation *location=[locations lastObject];
CLGeocoder *geocoder=[[CLGeocoder alloc]init];
[geocoder reverseGeocodeLocation:location completionHandler:^(NSArray *placemarks, NSError *error) {
CLPlacemark *placemark = placemarks[0];
NSDictionary *addressDictionary = [placemark addressDictionary];
}];
[self stopSignificantChangesUpdates];
}
- (void)stopSignificantChangesUpdates
{
[locationManager stopUpdatingLocation];
locationManager = nil;
}
My Question is, If the user location changes, how do I give the user an alert like Your location changed, you need to update it then only you can get a Nearby Restaurant Location popup should come once the user location changes otherwise don't want to call the didUpdateLocation everytime. I called startMonitoringSignificantLocationChanges then it did not called the didUpdateLocation in first time itself.Any Help on this.
check after some time or check after user's movement(whatever you want),if condition is true then call service...
I think it help you;
Step 1
(void)viewDidLoad {
[super viewDidLoad];
locationManager = [[CLLocationManager alloc] init];
//set the amount of metres travelled before location update is made
[locationManager setDistanceFilter:100];
locationManager.desiredAccuracy = kCLLocationAccuracyBest;
[locationManager startUpdatingLocation];
[locationManager requestAlwaysAuthorization];
// call the timer with 5 minutes cap using 5 * 60 = 300
[NSTimer scheduledTimerWithTimeInterval:300.0f target:self selector:#selector(sendlocation1) userInfo:nil repeats:YES];
Step 2
Every 100 Meter change Device This Method is called :
-(void)locationManager:(CLLocationManager *)manager
didUpdateToLocation:(CLLocation *)newLocation
fromLocation:(CLLocation *)oldLocation
{
NSLog(#"%f",newLocation.coordinate.latitude);
NSLog(#"%f",newLocation.coordinate.longitude);
CLLocationDistance meters = [newLocation distanceFromLocation:oldLocation];
if(meters >=100)
{
// call webservice for location is updated
[self sendlocation1];
}else
{
// call normal method
}
}
I kept Guided Access for iPad app. When the app is launched it asks for user's current location using CLLocationManager.This is working under Normal mode and updates user current location. But under Guided Access, popup ("Allow to access your location") is not shown and authorizationStatus is always kCLAuthorizationStatusNotDetermined and doesn't update current location of user . Couldn't understand what could be the problem.Searched a lot but couldn't find it.
ViewController.m :
- (void)viewDidAppear:(BOOL)animated
{
[appDelegate startLocation];
[self performSelector:#selector(CheckLocationManger) withObject:nil afterDelay:0.1];
}
-(void)CheckLocationManger
{
AppAppDelegate *appDelegate=(AppAppDelegate*)[[UIApplication sharedApplication]delegate];
if(![CLLocationManager locationServicesEnabled])
{
UIAlertView *alert1 = [[UIAlertView alloc] initWithTitle:#"Whoops we can’t find you!" message:#"Location services are disabled" delegate:nil cancelButtonTitle:#"OK" otherButtonTitles:nil];
if(activityIndictr)
[activityIndictr stopAnimating];
[alert1 show];
return;
}
if([CLLocationManager locationServicesEnabled])
{
if([CLLocationManager authorizationStatus]==kCLAuthorizationStatusDenied)
{
UIAlertView *alert1 = [[UIAlertView alloc] initWithTitle:#"Whoops we can’t find you!"message:#"Location services are disabled. You can fix this by going to Settings > Privacy > Location" delegate:nil cancelButtonTitle:#"OK" otherButtonTitles:nil];
if(activityIndictr)
[activityIndictr stopAnimating];
[alert1 show];
return;
}
if([CLLocationManager authorizationStatus]==kCLAuthorizationStatusNotDetermined) //This is called
{
[self performSelector:#selector(CheckLocationManger) withObject:self afterDelay:0.1];
return;
}
}
if(![self connected])
{
UIAlertView *alert1 = [[UIAlertView alloc] initWithTitle:#"Network Error" message:#"Please verify that you have internet connectivity" delegate:nil cancelButtonTitle:#"OK" otherButtonTitles:nil, nil];
if(activityIndictr)
[activityIndictr stopAnimating];
[alert1 show];
[alert1 release];
return;
}
else {
//continue further process
}
}
AppDelegate.m
- (void)startLocation
{
self.locationManager = [[[CLLocationManager alloc] init]autorelease];
self.locationManager.pausesLocationUpdatesAutomatically=NO;
[self.locationManager setDelegate:self];
if([[[UIDevice currentDevice ]systemVersion] floatValue]>=8.0)
{
if ([self.locationManager respondsToSelector:#selector(requestWhenInUseAuthorization)]) {
[self.locationManager requestWhenInUseAuthorization]; //is executed but popup never displays
}
}
[self.locationManager startUpdatingLocation];
}
Any suggestions would be helpful.Thank you !
At very first set NSLocationWhenInUseUsageDescription or NSLocationAlwaysUsageDescription in your .plist.
Add CoreLocation.framework and import in your class.h file -> #import <CoreLocation/CoreLocation.h> then set CLLocationManagerDelegate to your class.
Declare #property (strong, nonatomic) CLLocationManager *locationManager;
Init locationManager and set default value to it.
self.locationManager = [[CLLocationManager alloc] init];
self.locationManager.delegate = self;
self.locationManager.pausesLocationUpdatesAutomatically = NO;
[self.locationManager setDesiredAccuracy:kCLLocationAccuracyBestForNavigation];
[self.locationManager setDistanceFilter:200.0f];
if ([self.locationManager respondsToSelector:#selector(requestAlwaysAuthorization)]) // Or if ([self.locationManager respondsToSelector:#selector(requestWhenInUseAuthorization)])
[self.locationManager requestAlwaysAuthorization]; // Or [self.locationManager requestWhenInUseAuthorization];
[self.locationManager startUpdatingLocation];
Implement CLLocationMAnager delegate method
#pragma mark - Location Delegate
- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations
{
NSLog(#"updated coordinate are %#", [locations lastObject]);
CLLocation *currentLocation = [locations lastObject];
// Your code.....
}
I am trying to obtain current user location through my app. I wrote all delegate methods, added strings in info.plist but still it is not calling the delegate methods. Please help me.
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view.
self.locationManager = [[CLLocationManager alloc] init];
self.locationManager.delegate = self;
if(IS_OS_8_OR_LATER){
NSUInteger code = [CLLocationManager authorizationStatus];
if (code == kCLAuthorizationStatusNotDetermined &&([self.locationManager respondsToSelector:#selector(requestAlwaysAuthorization)] || [self.locationManager respondsToSelector:#selector(requestWhenInUseAuthorization)])) {
// choose one request according to your business.
if([[NSBundle mainBundle] objectForInfoDictionaryKey:#"NSLocationAlwaysUsageDescription"]){
[self.locationManager requestAlwaysAuthorization];
} else if([[NSBundle mainBundle] objectForInfoDictionaryKey:#"NSLocationWhenInUseUsageDescription"]) {
[self.locationManager requestWhenInUseAuthorization];
} else {
NSLog(#"Info.plist does not contain NSLocationAlwaysUsageDescription or NSLocationWhenInUseUsageDescription");
}
}
}
[self.locationManager startUpdatingLocation];
}
#pragma mark - CLLocationManagerDelegate
- (void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error
{
NSLog(#"didFailWithError: %#", error);
UIAlertView *errorAlert = [[UIAlertView alloc]
initWithTitle:#"Error" message:#"Failed to Get Your Location" delegate:nil cancelButtonTitle:#"OK" otherButtonTitles:nil];
[errorAlert show];
}
- (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation
{
NSLog(#"didUpdateToLocation: %#", newLocation);
CLLocation *currentLocation = newLocation;
if (currentLocation != nil) {
longitude = [NSString stringWithFormat:#"%.8f", currentLocation.coordinate.longitude];
latitude = [NSString stringWithFormat:#"%.8f", currentLocation.coordinate.latitude];
}
}
The console logs itself says that you are missing to add appropriate Keys in info.plist file
You are supposed to add
NSLocationWhenInUseUsageDescription
NSLocationAlwaysUsageDescription
keys with relevant description and then make a request from user to allow access.
This link might be helpful.
Since you have already added these keys try following
Remove the keys and re-add.
Once done try to do a clean and then build you application.