I have programmed a project which use CoreLocation. In this project, I designed a button to get location. However it has no reaction when I click. Someone said it had changed in iOS 8. And I do what he said. But it did't work. Here is my git link: https://github.com/dwjdwj1216/MyLocations
Do like this in your CurrentLocationViewController, getLocation Method change like this:-
locationManager = [[CLLocationManager alloc] init];
[locationManager setDelegate:self];
[locationManager setDesiredAccuracy:kCLLocationAccuracyBestForNavigation];
if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 8.0) {
[locationManager requestAlwaysAuthorization];
}
if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 9) {
_locationManager.allowsBackgroundLocationUpdates = YES;
}
[locationManager setDistanceFilter:10.0f];
[locationManager startUpdatingLocation];
[locationManager startMonitoringSignificantLocationChanges];
To Get Current Location, Follow step..
First Set Two lines in .Plist File
NSLocationAlwaysUsageDescription : Allow location
NSLocationWhenInUseUsageDescription : Allow location
// AppDelegate.h
#import <CoreLocation/CoreLocation.h>
#property (nonatomic,retain) CLLocationManager *locationManager;
#import "AppDelegate.m"
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
// Override point for customization after application launch.
[self getCurrentLocation];
}
#pragma mark - CLLocatin delegate && Location Methdos
-(void)getCurrentLocation {
locationManager = [[CLLocationManager alloc] init];
locationManager.delegate = self;
// To calculate loaction on 500 meters
/* CLLocationDistance kilometers = 0.5 1000.0; //user will be notified when distance is changed by 40km from current distance
locationManager.distanceFilter = kilometers; */
#ifdef __IPHONE_8_0
if (IS_OS_8_OR_LATER)
{
[locationManager requestAlwaysAuthorization];
}
#endif
[locationManager startUpdatingLocation];
}
- (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation {
//NSLog(#"didUpdateToLocation: %#", newLocation);
CLLocation *currentLocation = newLocation;
if (currentLocation != nil) {
[locationManager stopUpdatingLocation];
[self getCurrentCountry];
}
}
- (void)locationManager:(CLLocationManager*)aManager didFailWithError:(NSError *)anError {
switch([anError code])
{
case kCLErrorNetwork: // general, network-related error
{
}
break;
case kCLErrorDenied:{
}
break;
default:
{
}
break;
}
}
-(void)getCurrentCountry {
CLGeocoder *geoCoder = [[CLGeocoder alloc] init];
[geoCoder reverseGeocodeLocation:locationManager.location
completionHandler:^(NSArray *placemarks, NSError *error) {
if (error == nil && [placemarks count] > 0)
{
NSLog(#"Current country: %#", [[placemarks objectAtIndex:0] country]);
NSLog(#"Current country code: %#", [[placemarks objectAtIndex:0] ISOcountryCode]);
NSLog(#"CountryCode=%#",GetContryCode);
SetContryCode
setBoolForCountryCode(YES);
NSLog(#"CountryCode=%#",GetContryCode);
}
}];
}
Related
I am checking on device not on simulator and I want to fetch user's current location but it always shows location which I have set in edit scheme field from target of Xcode. I am using below code:
- (void)CurrentLocationIdentifier
{
//---- For getting current gps location
// locationManager = [CLLocationManager new];
locationManager=[[CLLocationManager alloc]init];
locationManager.delegate = self;
locationManager.distanceFilter = kCLDistanceFilterNone;
locationManager.desiredAccuracy = kCLLocationAccuracyBest;
if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 8.0)
[locationManager requestWhenInUseAuthorization];
[locationManager startUpdatingLocation];
}
-(void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error
{
if(kCLAuthorizationStatusDenied)
{
}
}
- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations
{
//currentLocation = [locations objectAtIndex:0];
currentLocation=[locations lastObject];
NSLog(#"location:%#",currentLocation);
[locationManager stopUpdatingLocation];
//[locationManager startUpdatingLocation];
geocoder = [[CLGeocoder alloc] init] ;
[geocoder reverseGeocodeLocation:currentLocation completionHandler:^(NSArray *placemarks, NSError *error)
{
if (!(error))
{
placemark = [placemarks objectAtIndex:0];
NSLog(#"\nCurrent Location Detected\n");
NSString *Country = [[NSString alloc]initWithString:placemark.ISOcountryCode];
NSString *state =[[NSString alloc]initWithString:placemark.administrativeArea];
//NSString *state =placemark.administrativeArea;
NSLog(#"%#",Country);
NSLog(#"administrativeArea>>%#",state);
self.stateLabel.text=state;
//[locationManager stopUpdatingLocation];
[[NSUserDefaults standardUserDefaults]setValue:Country forKey:#"countryISOCode"];
}
else
{
}
}];
[locationManager stopUpdatingLocation];
}
How to fetch exact country and state information of user?
I need to get the desired latitude and longitude of the image uploaded at my end at given location, so that I can use the same in future.
Try this one It may help ful to you
-(void) locationConfigureAppearance{
[m_LocationManager stopUpdatingLocation];
[m_LocationManager stopMonitoringSignificantLocationChanges];
m_LocationManager = [[CLLocationManager alloc] init];
m_LocationManager.desiredAccuracy = kCLLocationAccuracyKilometer;
m_LocationManager.delegate = self;
m_LocationManager.activityType = CLActivityTypeFitness;
if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 8.0)
{
[m_LocationManager requestWhenInUseAuthorization];
[m_LocationManager requestAlwaysAuthorization];
}
[m_LocationManager requestAlwaysAuthorization];
[m_LocationManager startUpdatingLocation];
}
#pragma mark - locationManager delegate Methods
- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations
{
CLLocation* newLocation = [locations lastObject];
m_GPSCoordinate = newLocation.coordinate;
self.SelectedLattitude = m_GPSCoordinate.latitude;
self.SelectedLongitude = m_GPSCoordinate.longitude;
NSLog(#"self.SelectedLattitude = %f %f",self.SelectedLattitude,self.SelectedLongitude);
}
I am using a iphone5s which i bought from US and using the same in India for development also using the indian carrier. I am trying to get the country code with NSLocale but this gives me the US, instead of IN.
What should i do to make it IN
NSLocale *currentLocale = [NSLocale currentLocale]; // get the current locale.
NSString *countryCode = [currentLocale objectForKey:NSLocaleCountryCode];
NSLog(#"country code %#",countryCode); //US
NSLocale's currentLocale will give you information about the locale set on the device settings (Language & Region).
If you want to get the country code of the carrier instead, you'll have to use CoreTelephony framework:
#import <CoreTelephony/CTTelephonyNetworkInfo.h>
#import <CoreTelephony/CTCarrier.h>
...
CTCarrier *carrier = [[CTTelephonyNetworkInfo new] subscriberCellularProvider];
NSString *countryCode = carrier.isoCountryCode;
A couple of things to watch for though:
The value for this property (isoCountryCode) is nil if any of the following apply:
The device is in Airplane mode.
There is no SIM card in the device.
The device is outside of cellular service range.
More info on the docs here
In Swift 3:
if let countryCode = (Locale.current as NSLocale).object(forKey: .countryCode) as? String {
print(countryCode)
}
To Get Country Code
You have to Follow below method
in Appdelegate.h file
//#import CoreLocation/CoreLocation.h>
#interface AppDelegate : UIResponder UIApplicationDelegate,CLLocationManagerDelegate>
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
[self getCurrentLocation];
}
#pragma mark - CLLocatin delegate && Location Methdos
-(void)getCurrentLocation {
locationManager = [[CLLocationManager alloc] init];
locationManager.delegate = self;
// To calculate loaction on 500 meters
/* CLLocationDistance kilometers = 0.5 1000.0; //user will be notified when distance is changed by 40km from current distance
locationManager.distanceFilter = kilometers; */
#ifdef __IPHONE_8_0
if (IS_OS_8_OR_LATER)
{
[locationManager requestAlwaysAuthorization];
}
#endif
[locationManager startUpdatingLocation];
}
- (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation {
//NSLog(#"didUpdateToLocation: %#", newLocation);
CLLocation *currentLocation = newLocation;
if (currentLocation != nil) {
[locationManager stopUpdatingLocation];
[self getCurrentCountry];
}
}
- (void)locationManager:(CLLocationManager*)aManager didFailWithError:(NSError *)anError {
switch([anError code])
{
case kCLErrorNetwork: // general, network-related error
{
}
break;
case kCLErrorDenied:{
}
break;
default:
{
}
break;
}
}
-(void)getCurrentCountry {
CLGeocoder *geoCoder = [[CLGeocoder alloc] init];
[geoCoder reverseGeocodeLocation:locationManager.location
completionHandler:^(NSArray *placemarks, NSError *error) {
if (error == nil && [placemarks count] > 0)
{
NSLog(#"Current country: %#", [[placemarks objectAtIndex:0] country]);
NSLog(#"Current country code: %#", [[placemarks objectAtIndex:0] ISOcountryCode]);
NSLog(#"CountryCode=%#",GetContryCode);
SetContryCode
setBoolForCountryCode(YES);
NSLog(#"CountryCode=%#",GetContryCode);
}
}];
}
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];