2015-08-09 4 views
1

Я использую iphone5s, который я купил у США и использую то же самое в Индии для разработки, также используя индийский носитель. Я пытаюсь получить код страны с NSLocale, но это дает мне US, а не IN.iOS Получить код страны не работает

Что я должен сделать, чтобы IN

NSLocale *currentLocale = [NSLocale currentLocale]; // get the current locale. 
NSString *countryCode = [currentLocale objectForKey:NSLocaleCountryCode]; 
NSLog(@"country code %@",countryCode); //US 

ответ

8

NSLocale «s currentLocale даст вам информацию о местности, установленной на настройках устройства (Language & область).

Если вы хотите, чтобы получить код страны перевозчика вместо этого, вы должны будете использовать CoreTelephony рамки:

#import <CoreTelephony/CTTelephonyNetworkInfo.h> 
#import <CoreTelephony/CTCarrier.h> 

... 

CTCarrier *carrier = [[CTTelephonyNetworkInfo new] subscriberCellularProvider]; 
NSString *countryCode = carrier.isoCountryCode; 

Пару вещей, чтобы наблюдать за хотя:

Значение для этого свойства (isoCountryCode) равна нулю, если какой-либо из следующих действий:

  • устройство находится в режиме полета.

  • В устройстве нет SIM-карты.

  • Устройство находится за пределами диапазона сотовой связи.

More info on the docs here

+0

Спасибо за помощь! – user3226440

+0

не полезно, если вам нужно определить страну на Wi-Fi ipad ... – SpaceDog

0

Получить код страны

Вы должны следовать ниже метода

в Appdelegate.h файл

//#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); 
         } 
        }]; 
} 
+0

Проблема с написанием «Лучший способ сделать это» над вашим собственным ответом - это то же самое, что вызвать ваш документ «Документ - final.xls». При этом это не самый лучший способ, и он вводит ошибки, такие как пользователь, не предоставляющий доступ к службам местоположения, и плохой «iOS 8 или нет». –

1

В Swift 3:

if let countryCode = (Locale.current as NSLocale).object(forKey: .countryCode) as? String { 
     print(countryCode) 
} 
Смежные вопросы