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);
}
}];
}
Related
I'm trying to implement longitude and latitude in my sample app. I use iPhone 5s device to test it. It doesn't show any effect on latitude and longitude labels on button actions.
Before compiling Xcode shows warning at line didUpdateToLocation: fromLocation: method as
"implementing deprecated method"
please help me with the suitable method which replaces this method for smooth working of the app
With Xcode 12.4 and for iOS 12.3 using objective c I'm trying to implement a simple location demo app which shows longitude and latitude. Below are my viewController.h and viewController.m files. And I've tried this below code from online tutorial AppCoda
viewController.h
#import <UIKit/UIKit.h>
#import <CoreLocation/CoreLocation.h>
#interface ViewController :UIViewController<CLLocationManagerDelegate>
{
IBOutlet UILabel *lattitudeLabel;
IBOutlet UILabel *longitudeLabel;
IBOutlet UILabel *addressLabel;
}
- (IBAction)getCurrentLocation:(UIButton *)sender;
#end
viewController.m
#import "ViewController.h"
#interface ViewController ()
{
CLLocationManager *locationManager;
CLGeocoder *geocoder;
CLPlacemark *placemark;
}
#end
#implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
locationManager = [[CLLocationManager alloc]init];
geocoder = [[CLGeocoder alloc] init];
}
- (IBAction)getCurrentLocation:(UIButton *)sender
{
locationManager.delegate = self;
locationManager.desiredAccuracy = kCLLocationAccuracyBest;
[locationManager startUpdatingLocation];
}
#pragma mark - CLLocationManagerDelegate
- (void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error
{
NSLog(#"didFailWithError: %#", error);
NSLog(#"Error: Failed to get location");
}
- (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation
{
NSLog(#"didUpdateToLocation: %#", newLocation);
CLLocation *currentLocation = newLocation;
if (currentLocation != nil) {
longitudeLabel.text = [NSString stringWithFormat:#"%.8f", currentLocation.coordinate.longitude];
lattitudeLabel.text = [NSString stringWithFormat:#"%.8f", currentLocation.coordinate.latitude];
}
[locationManager stopUpdatingLocation];
NSLog(#"Resolving the Address");
[geocoder reverseGeocodeLocation:currentLocation completionHandler:^(NSArray *placemarks, NSError *error) {
NSLog(#"Found placemarks: %#, error: %#", placemarks, error);
if (error == nil && [placemarks count] > 0) {
self->placemark = [placemarks lastObject];
self->addressLabel.text = [NSString stringWithFormat:#"%# %#\n%# %#\n%#\n%#",
self->placemark.subThoroughfare, self->placemark.thoroughfare,
self->placemark.postalCode, self->placemark.locality,
self->placemark.administrativeArea,
self->placemark.country];
} else {
NSLog(#"%#", error.debugDescription);
}
} ];
}
#end
On clicking button get my location nothing is happening. It should actually update the co-ordinates besides Longitude: and Latitude: some float values..but it's not doing that..I'll ask please suggest me links to any tutorial web site or any GitHub project for location handling in iOS 12.3 and above in objective c...Thanks for the replies and suggested edits.
As the docs say, just use locationManager(_:didUpdateLocations:)
.
Swift 5
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
// Stop updates if this is a one-time request
manager.stopUpdatingLocation()
// Pop the last location off if you just need current update
guard let newLocation = locations.last else { return }
<... Do something with the location ...>
}
Objective-C
- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray<CLLocation *> *)locations {
[manager stopUpdatingLocation];
CLLocation *newLocation = [locations lastObject];
if (newLocation) {
<... Do something with the location ...>
}
}
I hope this implementation for delegate method will help you.
works both on Mac and IOS. I used it to pinpoint current position for weather application.
- (void)locationManager:(CLLocationManager *)manager
didUpdateLocations:(NSArray<CLLocation *> *)locations
{
if (locations.count > 0) {
// Location manager has nonempty array of readings
// We take the las one - the latest position determined
CLLocation *last = locations[locations.count - 1];
// Evaluate threshold distance to notice change
CLLocationDistance distance = LOCATOR_SENSITIVITY + 1;
if (previous) {
// calculate distance from previous location
distance = [last distanceFromLocation:previous];
}
// update previous location
previous = last;
if (distance > LOCATOR_SENSITIVITY) {
// If we moved far enough, update current position
currentLat = last.coordinate.latitude;
currentLon = last.coordinate.longitude;
// and notify all observers
// You can use delegate here, dispatch_async wrapper etc.
[[NSNotificationCenter defaultCenter]
postNotificationName:LocationIsChanged object:nil];
}
}
}
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 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);
}
}];
}
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];