I have a problem with the refresh information on your GPS position.
The function given by me "locationManager" when you click the button does not refresh the information in the "Label".
My code: http://pastebin.com/hWeq6gTS
I am a novice programmer iOS. Please help.
The issue that is not always obvious with the location services is that you have to have one of these two keys in your Info.plist:
NSLocationWhenInUseUsageDescription
NSLocationAlwaysUsageDescription
Then, when starting updating of your position, don't forget to request permissions first (again, depending on your requirements (when in use/always):
[self.locationManager requestWhenInUseAuthorization]
[self.locationManager requestAlwaysAuthorization]
Add these two properties in info.plist
'NSLocationAlwaysUsageDescription' and below property
Create CocoaTouch Class 'LocationManager' inherit from NSObject like below class.
Singleton Location Manager Class .h
#import <Foundation/Foundation.h>
#interface LocationManager : NSObject <CLLocationManagerDelegate>
{
CLLocationManager *locationManager;
}
#property (strong, nonatomic) NSString *longitude;
#property (strong, nonatomic) NSString *latitude;
#property (strong, nonatomic) CLLocation *currentLocation;
+ (instancetype)sharedInstance;
#end
Implementation here .m
#import "LocationManager.h"
#implementation LocationManager
- (id) init
{
self = [super init];
if (self != nil)
{
[self locationManager];
}
return self;
}
+ (instancetype)sharedInstance
{
static LocationManager *sharedInstance = nil;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
sharedInstance = [[LocationManager alloc] init];
// Do any other initialisation stuff here
});
return sharedInstance;
}
- (void) locationManager
{
if ([CLLocationManager locationServicesEnabled])
{
locationManager = [[CLLocationManager alloc] init];
locationManager.delegate = self;
locationManager.desiredAccuracy = kCLLocationAccuracyBest;
locationManager.distanceFilter = kCLDistanceFilterNone;
if ([locationManager respondsToSelector:#selector(requestWhenInUseAuthorization)])
{
[locationManager requestWhenInUseAuthorization];
}
[locationManager startUpdatingLocation];
}
else{
UIAlertView *servicesDisabledAlert = [[UIAlertView alloc] initWithTitle:#"Location Services Disabled" message:#"You currently have all location services for this device disabled. If you proceed, you will be showing past informations. To enable, Settings->Location->location services->on" delegate:nil cancelButtonTitle:#"Ok" otherButtonTitles:#"Continue",nil];
[servicesDisabledAlert show];
[servicesDisabledAlert setDelegate:self];
}
}
- (void)requestWhenInUseAuthorization
{
CLAuthorizationStatus status = [CLLocationManager authorizationStatus];
// If the status is denied or only granted for when in use, display an alert
if (status == kCLAuthorizationStatusAuthorizedWhenInUse || status == kCLAuthorizationStatusDenied) {
NSString *title;
title = (status == kCLAuthorizationStatusDenied) ? #"Location services are off" : #"Background location is not enabled";
NSString *message = #"To use background location you must turn on 'Always' in the Location Services Settings";
UIAlertView *alertViews = [[UIAlertView alloc] initWithTitle:title
message:message
delegate:self
cancelButtonTitle:#"Cancel"
otherButtonTitles:#"Settings", nil];
[alertViews show];
}
// The user has not enabled any location services. Request background authorization.
else if (status == kCLAuthorizationStatusNotDetermined) {
[locationManager requestWhenInUseAuthorization];
}
}
#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 didChangeAuthorizationStatus:(CLAuthorizationStatus)status
{
switch (status) {
case kCLAuthorizationStatusNotDetermined:
case kCLAuthorizationStatusRestricted:
case kCLAuthorizationStatusDenied:
{
// do some error handling
}
break;
default:{
[locationManager startUpdatingLocation];
}
break;
}
}
- (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation {
CLLocation *location;
location = [manager location];
CLLocationCoordinate2D coordinate = [location coordinate];
_currentLocation = [[CLLocation alloc] init];
_currentLocation = newLocation;
_longitude = [NSString stringWithFormat:#"%f",coordinate.longitude];
_latitude = [NSString stringWithFormat:#"%f",coordinate.latitude];
// globalObjects.longitude = [NSString stringWithFormat:#"%f",coordinate.longitude];
// globalObjects.latitude = [NSString stringWithFormat:#"%f",coordinate.latitude];
}
#end
import
#import "LocationManager.h"
in your AppDelegate.h
and call that in your AppDelegate.m's like this
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
[LocationManager sharedInstance];
return true;
}
Then just get
[LocationManager sharedInstance].longitude or latitude for updated lat long.
Instead of using
-(void)locationManager:(CLLocationManager *)manager
didUpdateToLocation:(CLLocation *)newLocation
fromLocation:(CLLocation *)oldLocation{
// Location update code
}
use this function to get updated location
-(void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations{
// Assigning the last object as the current location of the device
CLLocation *currentLocation = [locations lastObject];
}
Sometimes we do face problem when we do not check the authorisation status. You can check this code
// Custom initialization code
CLLocationManager *manager = [[CLLocationManager alloc]init];
manager.delegate = self;
manager.desiredAccuracy = kCLLocationAccuracyBest;
// Setting distance fiter to 10 to get notified only after location change about 10 meter
manager.distanceFilter = kCLDistanceFilterNone;
// Requesting for authorization
if ([manager respondsToSelector:#selector(requestWhenInUseAuthorization)]){
[manager requestWhenInUseAuthorization];
}
// Immediately starts updating the location
[manager startUpdatingLocation];
[manager startUpdatingHeading];
if __IPHONE_OS_VERSION_MAX_ALLOWED >= 80000
// user activated automatic attraction info mode
CLAuthorizationStatus status = [CLLocationManager authorizationStatus];
if (status == kCLAuthorizationStatusDenied ||
status == kCLAuthorizationStatusAuthorizedWhenInUse ||
status == kCLAuthorizationStatusNotDetermined) {
// present an alert indicating location authorization required
// and offer to take the user to Settings for the app via
// UIApplication -openUrl: and UIApplicationOpenSettingsURLString
[manager requestAlwaysAuthorization];
}
[manager requestWhenInUseAuthorization];
else
[manager requestAlwaysAuthorization];
endif
Related
I have to find the current location and i am using this code
-(CLLocationCoordinate2D) getLocation{
locationManager = [[CLLocationManager alloc] init];
locationManager.delegate = self;
locationManager.desiredAccuracy = kCLLocationAccuracyBest;
locationManager.distanceFilter = kCLDistanceFilterNone;
[locationManager startUpdatingLocation];
CLLocation *location = [locationManager location];
CLLocationCoordinate2D coordinate = [location coordinate];
return coordinate;
}
- (void)getCurrentLocation{
CLLocationCoordinate2D coordinate = [self getLocation];
NSString *latitude = [NSString stringWithFormat:#"%f", coordinate.latitude];
NSString *longitude = [NSString stringWithFormat:#"%f", coordinate.longitude];
NSLog(#"Latitude = %#", latitude);
NSLog(#"Longitude = %#", longitude);
}
but latitude and longitude is coming zero? and i have called these method in viewDidLoad
[self getCurrentLocation];
[self getLocation];
why is it so please help me. thanks
I hope , Following info can help you:
#import <UIKit/UIKit.h>
#import <CoreLocation/CoreLocation.h>
#interface yourController : UIViewController <CLLocationManagerDelegate> {
CLLocationManager *locationManager;
}
#end
and add this:
locationManager = [[CLLocationManager alloc] init];
locationManager.delegate = self;
locationManager.distanceFilter = kCLDistanceFilterNone;
locationManager.desiredAccuracy = kCLLocationAccuracyBest;
if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 8.0)
[self.locationManager requestWhenInUseAuthorization];
[locationManager startUpdatingLocation];
Callback function
- (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation {
NSLog(#"OldLocation %f %f", oldLocation.coordinate.latitude, oldLocation.coordinate.longitude);
NSLog(#"NewLocation %f %f", newLocation.coordinate.latitude, newLocation.coordinate.longitude);
}
You also have to add a string for the
[`NSLocationAlwaysUsageDescription`]
You need to use "CLLocationManagerDelegate".
Just go through this tutorial. How To Get the User Location in iPhone App
Here you will learn about CoreLocation Framework.
This is the delegate method which will return you current lat-long.
- (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation
And also make sure your app authorize to use location services.
And Also run your app on device, or if you want to see the result in simulator, follow the steps mentioned in tutorial.
Step 1 : #import <CoreLocation/CoreLocation.h> import framework. Also add framework in your project.
Step 2 : Make sure your view-controller implement CLLocationManagerDelegate
#interface MyLocationViewController : UIViewController <CLLocationManagerDelegate>
Step 3 : Define class instance of CLLocationManager
#implementation MyLocationViewController {
CLLocationManager *locationManager;
}
Step 4 :
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
locationManager = [[CLLocationManager alloc] init];
if([locationManager respondsToSelector:#selector(requestAlwaysAuthorization)]) {
//iOS 8.0 onwards
[locationManager requestAlwaysAuthorization];
}
locationManager.delegate = self;
locationManager.desiredAccuracy = kCLLocationAccuracyBest;
[locationManager startUpdatingLocation];
}
Step 5 : Here is your CLLocationManagerDelegate
method implementation
- (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) {
NSLog(#"Longitude %.8f",currentLocation.coordinate.longitude);
NSLog(#"Latitude %.8f",currentLocation.coordinate.latitude);
}
}
First go to your info.plist and right click on it and select the source code option.
Then add the following lines after the <dict> keyword
<key>NSLocationAlwaysUsageDescription</key>
<string>This App wants to Know your location</string>
<key>NSLocationWhenInUseUsageDescription</key>
<string>This App wants to Know your location</string>
Without this, you can't get CLLocation working in iOS 9.0.
Now follow the instruction.
Import
#import <CoreLocation/CoreLocation.h>
and list the CoreLocation delegate like
#interface ViewController ()<CLLocationManagerDelegate>
#property (strong, nonatomic) CLLocationManager *locationManager;
#end
Then in the viewDidLoad method add the following lines-
self.locationManager = [[CLLocationManager alloc]init];
self.locationManager.delegate=self;
self.locationManager.desiredAccuracy = kCLLocationAccuracyBest;
if ([self.locationManager respondsToSelector:#selector(requestWhenInUseAuthorization)]){
[self.locationManager requestWhenInUseAuthorization];
}
[self.locationManager startUpdatingLocation];
Now implement the delegate methods
- (void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error
{
NSLog(#"didFailWithError: %#", error);
UIAlertView *errorAlert = [[UIAlertView alloc]
initWithTitle:#"Sorry"
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) {
NSLog(#"%#", [NSString stringWithFormat:#"%.4f", currentLocation.coordinate.longitude]);
NSLog(#"%#", [NSString stringWithFormat:#"%.4f", currentLocation.coordinate.latitude]);
}
}
It takes some time for the CLLocationManager to get the coordinates. Therefore, the CLLocationManager uses a delegate to notify when it received the location updates. Therefore, you cannot get the result immediately. Please have a look at this post to see how it's done.
Well, I wanted you to read the doc, still I am posting the solution.
-(void)viewDidLoad{
[self initLocationManager];
}
-(void)initLocationManager{
self.locationManager=[[CLLocationManager alloc] init];
self.locationManager.delegate=self;
if (([_locationManager respondsToSelector:#selector(requestWhenInUseAuthorization)])) {
[_locationManager requestWhenInUseAuthorization];
}
self.locationManager.desiredAccuracy = kCLLocationAccuracyBest;
self.locationManager.distanceFilter = kCLDistanceFilterNone;
[self.locationManager startUpdatingLocation];
}
Then handle the location updates in the CLLocationManager delegate method like below
-(void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray<CLLocation *> *)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) < 15.0) {
NSLog(#"%f,%f",location.coordinate.latitude,location.coordinate.longitude);
}
}
Update
To make it work, you need to do two things
Enable Background Modes from Capabilities Tab, and choose Location Updates, see image below
Add NSLocationWhenInUseUsageDescription in Info Tab, into the plist, see image
It will start working.
Hope it helps. Cheers.
Use this code it works
firstly add NSLocationAlwaysUsageDescription as string in info.plist
in .h
#import <CoreLocation/CoreLocation.h>
#interface ExamListVC : UIViewController<CLLocationManagerDelegate>
{
CLLocationManager * locationManager;
}
#end
in .m use this code
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view.
locationManager . delegate = self;
[self initLocationManager];
}
-(void)initLocationManager
{
locationManager=[[CLLocationManager alloc] init];
locationManager.delegate=self;
if (([locationManager respondsToSelector:#selector(requestWhenInUseAuthorization)]))
{
[locationManager requestWhenInUseAuthorization];
}
locationManager.desiredAccuracy = kCLLocationAccuracyBest;
locationManager.distanceFilter = kCLDistanceFilterNone;
[locationManager startUpdatingLocation];
}
-(void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations
{
CLLocation* location = [locations lastObject];
NSDate* eventDate = location.timestamp;
NSTimeInterval howRecent = [eventDate timeIntervalSinceNow];
if (abs(howRecent) < 15.0)
{
NSLog(#"Current Coordinates are %f,%f",location.coordinate.latitude,location.coordinate.longitude);
[locationManager stopUpdatingLocation];
}
}
it will give output like
[2390:96060] Current Coordinates are 37.332331,-122.031219
I have to find the current location and i am using this code
-(CLLocationCoordinate2D) getLocation{
locationManager = [[CLLocationManager alloc] init];
locationManager.delegate = self;
locationManager.desiredAccuracy = kCLLocationAccuracyBest;
locationManager.distanceFilter = kCLDistanceFilterNone;
[locationManager startUpdatingLocation];
CLLocation *location = [locationManager location];
CLLocationCoordinate2D coordinate = [location coordinate];
return coordinate;
}
- (void)getCurrentLocation{
CLLocationCoordinate2D coordinate = [self getLocation];
NSString *latitude = [NSString stringWithFormat:#"%f", coordinate.latitude];
NSString *longitude = [NSString stringWithFormat:#"%f", coordinate.longitude];
NSLog(#"Latitude = %#", latitude);
NSLog(#"Longitude = %#", longitude);
}
but latitude and longitude is coming zero? and i have called these method in viewDidLoad
[self getCurrentLocation];
[self getLocation];
why is it so please help me. thanks
I hope , Following info can help you:
#import <UIKit/UIKit.h>
#import <CoreLocation/CoreLocation.h>
#interface yourController : UIViewController <CLLocationManagerDelegate> {
CLLocationManager *locationManager;
}
#end
and add this:
locationManager = [[CLLocationManager alloc] init];
locationManager.delegate = self;
locationManager.distanceFilter = kCLDistanceFilterNone;
locationManager.desiredAccuracy = kCLLocationAccuracyBest;
if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 8.0)
[self.locationManager requestWhenInUseAuthorization];
[locationManager startUpdatingLocation];
Callback function
- (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation {
NSLog(#"OldLocation %f %f", oldLocation.coordinate.latitude, oldLocation.coordinate.longitude);
NSLog(#"NewLocation %f %f", newLocation.coordinate.latitude, newLocation.coordinate.longitude);
}
You also have to add a string for the
[`NSLocationAlwaysUsageDescription`]
You need to use "CLLocationManagerDelegate".
Just go through this tutorial. How To Get the User Location in iPhone App
Here you will learn about CoreLocation Framework.
This is the delegate method which will return you current lat-long.
- (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation
And also make sure your app authorize to use location services.
And Also run your app on device, or if you want to see the result in simulator, follow the steps mentioned in tutorial.
Step 1 : #import <CoreLocation/CoreLocation.h> import framework. Also add framework in your project.
Step 2 : Make sure your view-controller implement CLLocationManagerDelegate
#interface MyLocationViewController : UIViewController <CLLocationManagerDelegate>
Step 3 : Define class instance of CLLocationManager
#implementation MyLocationViewController {
CLLocationManager *locationManager;
}
Step 4 :
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
locationManager = [[CLLocationManager alloc] init];
if([locationManager respondsToSelector:#selector(requestAlwaysAuthorization)]) {
//iOS 8.0 onwards
[locationManager requestAlwaysAuthorization];
}
locationManager.delegate = self;
locationManager.desiredAccuracy = kCLLocationAccuracyBest;
[locationManager startUpdatingLocation];
}
Step 5 : Here is your CLLocationManagerDelegate
method implementation
- (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) {
NSLog(#"Longitude %.8f",currentLocation.coordinate.longitude);
NSLog(#"Latitude %.8f",currentLocation.coordinate.latitude);
}
}
First go to your info.plist and right click on it and select the source code option.
Then add the following lines after the <dict> keyword
<key>NSLocationAlwaysUsageDescription</key>
<string>This App wants to Know your location</string>
<key>NSLocationWhenInUseUsageDescription</key>
<string>This App wants to Know your location</string>
Without this, you can't get CLLocation working in iOS 9.0.
Now follow the instruction.
Import
#import <CoreLocation/CoreLocation.h>
and list the CoreLocation delegate like
#interface ViewController ()<CLLocationManagerDelegate>
#property (strong, nonatomic) CLLocationManager *locationManager;
#end
Then in the viewDidLoad method add the following lines-
self.locationManager = [[CLLocationManager alloc]init];
self.locationManager.delegate=self;
self.locationManager.desiredAccuracy = kCLLocationAccuracyBest;
if ([self.locationManager respondsToSelector:#selector(requestWhenInUseAuthorization)]){
[self.locationManager requestWhenInUseAuthorization];
}
[self.locationManager startUpdatingLocation];
Now implement the delegate methods
- (void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error
{
NSLog(#"didFailWithError: %#", error);
UIAlertView *errorAlert = [[UIAlertView alloc]
initWithTitle:#"Sorry"
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) {
NSLog(#"%#", [NSString stringWithFormat:#"%.4f", currentLocation.coordinate.longitude]);
NSLog(#"%#", [NSString stringWithFormat:#"%.4f", currentLocation.coordinate.latitude]);
}
}
It takes some time for the CLLocationManager to get the coordinates. Therefore, the CLLocationManager uses a delegate to notify when it received the location updates. Therefore, you cannot get the result immediately. Please have a look at this post to see how it's done.
Well, I wanted you to read the doc, still I am posting the solution.
-(void)viewDidLoad{
[self initLocationManager];
}
-(void)initLocationManager{
self.locationManager=[[CLLocationManager alloc] init];
self.locationManager.delegate=self;
if (([_locationManager respondsToSelector:#selector(requestWhenInUseAuthorization)])) {
[_locationManager requestWhenInUseAuthorization];
}
self.locationManager.desiredAccuracy = kCLLocationAccuracyBest;
self.locationManager.distanceFilter = kCLDistanceFilterNone;
[self.locationManager startUpdatingLocation];
}
Then handle the location updates in the CLLocationManager delegate method like below
-(void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray<CLLocation *> *)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) < 15.0) {
NSLog(#"%f,%f",location.coordinate.latitude,location.coordinate.longitude);
}
}
Update
To make it work, you need to do two things
Enable Background Modes from Capabilities Tab, and choose Location Updates, see image below
Add NSLocationWhenInUseUsageDescription in Info Tab, into the plist, see image
It will start working.
Hope it helps. Cheers.
Use this code it works
firstly add NSLocationAlwaysUsageDescription as string in info.plist
in .h
#import <CoreLocation/CoreLocation.h>
#interface ExamListVC : UIViewController<CLLocationManagerDelegate>
{
CLLocationManager * locationManager;
}
#end
in .m use this code
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view.
locationManager . delegate = self;
[self initLocationManager];
}
-(void)initLocationManager
{
locationManager=[[CLLocationManager alloc] init];
locationManager.delegate=self;
if (([locationManager respondsToSelector:#selector(requestWhenInUseAuthorization)]))
{
[locationManager requestWhenInUseAuthorization];
}
locationManager.desiredAccuracy = kCLLocationAccuracyBest;
locationManager.distanceFilter = kCLDistanceFilterNone;
[locationManager startUpdatingLocation];
}
-(void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations
{
CLLocation* location = [locations lastObject];
NSDate* eventDate = location.timestamp;
NSTimeInterval howRecent = [eventDate timeIntervalSinceNow];
if (abs(howRecent) < 15.0)
{
NSLog(#"Current Coordinates are %f,%f",location.coordinate.latitude,location.coordinate.longitude);
[locationManager stopUpdatingLocation];
}
}
it will give output like
[2390:96060] Current Coordinates are 37.332331,-122.031219
I'm trying to use core location in iOS 8 simulator, for that I added in my view an object of type 'MapKit View', In tab Atributtes inspector is checked the option show user location, In my project I'm using ARC, below is the structure of my code:
ViewController.h
#import <UIKit/UIKit.h>
#import <CoreLocation/CoreLocation.h>
#import <MapKit/MapKit.h>
#interface MeuPrimeiroViewController : UIViewController <MKMapViewDelegate, CLLocationManagerDelegate>{
IBOutlet MKMapView *mapView;
}
#property (nonatomic, strong) CLLocationManager *locationManager;
#end
ViewController.m
#synthesize locationManager;
- (void)viewDidLoad {
[super viewDidLoad];
if ([CLLocationManager locationServicesEnabled]) {
NSLog(#"CLLocationManager locationServicesEnabled == ON");
locationManager = [[CLLocationManager alloc] init];
locationManager.delegate = self;
locationManager.distanceFilter = kCLDistanceFilterNone;
locationManager.desiredAccuracy = kCLLocationAccuracyBest;
// Check for iOS 8 Vs earlier version like iOS7.Otherwise code will
// crash on ios 7
if ([locationManager respondsToSelector:#selector
(requestWhenInUseAuthorization)]) {
[locationManager requestAlwaysAuthorization];
}
[locationManager startUpdatingLocation];
}else{
NSLog(#"CLLocationManager locationServicesEnabled == OFF");
}
}
- (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation{
NSLog(#"It works this method is called");
}
-(void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error{
NSLog(#"Error: %#",[error description]);
}
In my info.plist file I add this key (NSLocationAlwaysUsageDescription) with this value (String).
If I go to attributes inspector and enable the checkbox (shows user location) I receive this error message, and core location methods are not called:
Trying to start MapKit location updates without prompting for location authorization. Must call -[CLLocationManager requestWhenInUseAuthorization] or -[CLLocationManager requestAlwaysAuthorization] first.
If I disable the checkbox, this message disappear, and core location methods not called again. I try to change the navigation to londom, try to change location to free run but nothing I tried worked, the methods do not continue to be called and never showed an empowering message to use core location. I believe I've already tried everything, anyone have any suggestions or a solution to this problem?
This is what i am doing for my app and working perfectly
- (void)startSignificantChangeUpdates {
if (nil == self.locationManager) {
self.locationManager = [[CLLocationManager alloc] init];
}
self.locationManager.delegate = self;
[self.locationManager startMonitoringSignificantLocationChanges];
}
- (void)locationManager:(CLLocationManager *)manager
didUpdateLocations:(NSArray *)locations {
CLLocation* location = [locations lastObject];
if (location) {
self.currentLocation = location;
NSString *latitude = [NSString stringWithFormat:#"%f", location.coordinate.latitude];
NSString *longitude = [NSString stringWithFormat:#"%f", location.coordinate.longitude];
self.latLong = [NSString stringWithFormat:#"%#,%#",latitude, longitude];
}
if (!self.geocoder)
self.geocoder = [[CLGeocoder alloc] init];
[self.geocoder reverseGeocodeLocation:location completionHandler:
^(NSArray* placemarks, NSError* error){
if ([placemarks count] > 0) {
CLPlacemark *placemark = [placemarks objectAtIndex:0];
if (placemark.postalCode) {
self.currentZipCode = placemark.postalCode;
}
[[NSNotificationCenter defaultCenter] postNotificationName:#"zipCodeFoundNotification" object:self.currentZipCode userInfo:nil];
} else {
[[NSNotificationCenter defaultCenter] postNotificationName:#"zipCodeFoundNotification" object:nil userInfo:nil];
}
}];
}
- (void)locationManager:(CLLocationManager *)manager didChangeAuthorizationStatus:(CLAuthorizationStatus)status {
if (status != kCLAuthorizationStatusAuthorized && status != kCLAuthorizationStatusNotDetermined) {
if (status == kCLAuthorizationStatusDenied){
self.currentZipCode = #"kCLAuthorizationStatusDenied";
} else if (status == kCLAuthorizationStatusRestricted) {
self.currentZipCode = #"kCLAuthorizationStatusRestricted";
}
}
}
i want to find the current location of the user
below the code for finding coordinates from the well defined adress
hom can i find the current location of the user ..please help me
.h file
#import
#import
#interface ViewController : UIViewController<MKMapViewDelegate,CLLocationManagerDelegate>
#property(nonatomic,retain) MKMapView *myMapView;
#property (nonatomic, strong) CLGeocoder *myGeocoder;
#end
.m file
#import "ViewController.h"
#import <CoreLocation/CoreLocation.h>
#interface ViewController ()
{
CLLocationManager *locationManager;
}
#end
#implementation ViewController
- (void)viewDidLoad
{
[super viewDidLoad];
self.myMapView.showsUserLocation=YES;
self.view.backgroundColor=[UIColor whiteColor];
self.myMapView=[[MKMapView alloc]initWithFrame:self.view.bounds];
self.myMapView.mapType=MKMapTypeHybrid;
self.myMapView.autoresizingMask=UIViewAutoresizingFlexibleWidth|UIViewAutoresizingFlexibleHeight;
[self.view addSubview:self.myMapView];
locationManager = [[CLLocationManager alloc] init];
locationManager.delegate=self;
locationManager.desiredAccuracy=kCLLocationAccuracyBest;
locationManager.distanceFilter=kCLDistanceFilterNone;
[locationManager startUpdatingLocation];
NSString *oreillyAddress =#"india";
self.myGeocoder = [[CLGeocoder alloc] init];
[self.myGeocoder
geocodeAddressString:oreillyAddress completionHandler:^(NSArray *placemarks, NSError *error)
{
if ([placemarks count] > 0 && error == nil)
{
NSLog(#"Found %lu placemark(s).", (unsigned long)[placemarks count]);
CLPlacemark *firstPlacemark = [placemarks objectAtIndex:0]; NSLog(#"Longitude = %f", firstPlacemark.location.coordinate.longitude); NSLog(#"Latitude = %f", firstPlacemark.location.coordinate.latitude);
}
else if ([placemarks count] == 0 &&
error == nil){ NSLog(#"Found no placemarks.");
}
else if (error != nil){
NSLog(#"An error occurred = %#", error); }
}];
// Do any additional setup after loading the view, typically from a nib.
}
-(BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation
{
return YES;
}
- (void)locationManager:(CLLocationManager *)manager
didUpdateToLocation:(CLLocation *)newLocation
fromLocation:(CLLocation *)oldLocation
{
float latitude=newLocation.coordinate.latitude;
float longitude=newLocation.coordinate.longitude;
NSLog(#"%f",latitude);
NSLog(#"%f",longitude);
[locationManager stopUpdatingLocation];
}
- (void)locationManager:(CLLocationManager *)manager
didFailWithError:(NSError *)error
{
NSLog(#"error==>%#",error);
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
#end
Define
CLLocationManager *lm;
CLLocation *location;
and then add the below mentioned code in your ViewDidLoad method
lm = [[CLLocationManager alloc] init];
lm.delegate = self;
lm.desiredAccuracy = kCLLocationAccuracyBestForNavigation;
lm.distanceFilter = kCLDistanceFilterNone;
[lm startUpdatingLocation];
location = [lm location];
CLLocationCoordinate2D coordinate;
coordinate.longitude = location.coordinate.longitude;
coordinate.latitude = location.coordinate.latitude;
if((location.coordinate.longitude== 0.0 ) && (location.coordinate.latitude==0.0))
{
UIAlertView *alert2 = [[UIAlertView alloc ] initWithTitle:(#"Server Error:")message:(#"Internet Problem. Try Later !!!") delegate:nil cancelButtonTitle:nil otherButtonTitles:(#"OK"), nil];
[alert2 show];
}
else
{
coordinate = [location coordinate];
NSLog(#"Latitude of User is %f",coordinate.longitude);
NSLog(#"Longitude of User is %f",coordinate.latitude);
}
Use this
self.myMapView.showsUserLocation = YES;
If you are using the simulator, you would need to go to: Debug -> Location -> Customer. From there set your location to the desired test point.
To get user's current location in iOS 8
Add <CLLocationManagerDelegate> in .h file.
CLLocationManager *locationManager;
CLLocation *currentLocation;
locationManager = [CLLocationManager new];
if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 8.0 && [CLLocationManager authorizationStatus] != kCLAuthorizationStatusAuthorizedWhenInUse)
{
[locationManager requestAlwaysAuthorization];
}
locationManager.delegate = self;
locationManager.desiredAccuracy = kCLLocationAccuracyBest;
locationManager.distanceFilter = kCLDistanceFilterNone;
[locationManager startUpdatingLocation];
- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations {
CLLocation *location = [locations lastObject];
NSLog(#"lat%f - lon%f", location.coordinate.latitude, location.coordinate.longitude);
NSString *currentLatitude = [NSString stringWithFormat:#"%f",location.coordinate.latitude];
NSString *currentLongitude = [NSString stringWithFormat:#"%f",location.coordinate.longitude];
[locationManager stopUpdatingLocation];
}
-(void)locationManager:(CLLocationManager *)manager didChangeAuthorizationStatus:(CLAuthorizationStatus)status
{
switch (status)
{
case kCLAuthorizationStatusNotDetermined:
case kCLAuthorizationStatusRestricted:
case kCLAuthorizationStatusDenied:
{
[locationManager requestAlwaysAuthorization];
}
break;
default:
{
[locationManager startUpdatingLocation];
}
break;
}
}
- (void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error
{
NSLog(#"Error while getting core location : %#",[error localizedFailureReason]);
if ([error code] == kCLErrorDenied)
{
//you had denied
}
[manager stopUpdatingLocation];
}
And In your plist file Dont forget to Enter a key
NSLocationAlwaysUsageDescription
Use this:
[self.mapview setShowsUserLocation:YES];
I want to get the coordinates of the user, once user starts the app it should initialise GPS coordinates. I have followed this tutorial:
http://www.iosdevnotes.com/2011/10/ios-corelocation-tutorial/
I have created a class named CurrentLocationWithGPS
This is the header:
#import <Foundation/Foundation.h>
#import <CoreLocation/CoreLocation.h>
#interface CurrentLocationWithGPS : NSObject<CLLocationManagerDelegate>
- (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation;
- (void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error;
- (void) getLocations;
- (Float32) latitude;
#property (strong, nonatomic) CLLocationManager *locationManager;
#property (strong, nonatomic) CLLocation *currentLocation;
#end
This is the implementation:
#import "CurrentLocationWithGPS.h"
#implementation CurrentLocationWithGPS
#synthesize locationManager, currentLocation;
- (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation {
self.currentLocation = newLocation;
if(newLocation.horizontalAccuracy <= 100.0f) { [locationManager stopUpdatingLocation]; }
}
- (void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error {
if(error.code == kCLErrorDenied) {
[locationManager stopUpdatingLocation];
} else if(error.code == kCLErrorLocationUnknown) {
// retry
} else {
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Error retrieving location"
message:[error description]
delegate:nil
cancelButtonTitle:#"OK"
otherButtonTitles:nil];
[alert show];
}
}
- (void) getLocations {
NSLog(#"GPS Location is initialising...");
locationManager = [[CLLocationManager alloc] init];
locationManager.delegate = self;
[locationManager startUpdatingLocation];
NSLog(#"GPS Location is initialised...");
}
- (Float32) latitude {
return currentLocation.coordinate.latitude;
}
- (Float32) longitude {
return currentLocation.coordinate.longitude;
}
#end
I call the getLocations function in a separate thread so that it wouldn't block anything else. Here is how I call it from another class:
- (void)viewDidLoad
{
[super viewDidLoad];
NSThread *myThread =[[NSThread alloc]initWithTarget:self selector:#selector(locationSet) object:nil];
[myThread start];
}
- (void) locationSet {
CurrentLocationWithGPS *locationFind = [[CurrentLocationWithGPS alloc] init];
locationFind.getLocations;
NSLog(#"latitude is %f", locationFind.latitude);
}
Now the problem is both latitude and longitdute functions are returning 0.000, what am I missing here? I am developing for iOS6.1.
First conforms CLLocationManagerDelegate in .h file like this
#interface CurrentLocationWithGPS : NSObject<CLLocationManagerDelegate>
You need to set CLLocation's Delegate in this method.
- (void) getLocations
{
NSLog(#"GPS Location is initialising...");
locationManager = [[CLLocationManager alloc] init];
locationManager.delegate = self;
locationManager.desiredAccuracy = kCLLocationAccuracyBest;
locationManager.distanceFilter = kCLDistanceFilterNone;
[locationManager startUpdatingLocation];
NSLog(#"GPS Location is initialised...");
}
Do you getting the Current Location on the output . Or R you just trying to retrieve the Co-ordinates ?..
It's still confusing , anyhow
Put this part of code on Your getLocations method
I Hope that You are not at all checking with Location Services . You
Should enable the LocationServices for your app else You always get
null values Check with the Condition:
if ([CLLocationManager locationServicesEnabled])
{
}
For Example :
CLLocationManager *locationManager = [[CLLocationManager alloc] init];
if ([CLLocationManager locationServicesEnabled])
{
locationManager.delegate = self;
locationManager.desiredAccuracy = kCLLocationAccuracyBest;
locationManager.distanceFilter = kCLDistanceFilterNone;
[locationManager startUpdatingLocation];
}
location = [locationManager location];
CLLocationCoordinate2D coordinate = [location coordinate];;
NSString *str=[[NSString alloc] initWithFormat:#" latitude:%f longitude:%f",coordinate.latitude,coordinate.longitude];
And Let me know , .????