Programing

iOS에서 기기 위치 (국가 만 해당) 가져 오기

lottogame 2020. 12. 10. 08:26
반응형

iOS에서 기기 위치 (국가 만 해당) 가져 오기


iOS 기기의 국가 위치를 확인해야합니다.

MKReverseGeocoder와 함께 CoreLocation을 사용하려고했습니다. 그러나 이것은 매우 자주 불규칙하게 반환되는 것 같습니다. 그리고 나는 나라 만 필요하고 거리 등은 필요하지 않습니다.

더 안정적인 방법으로 어떻게 할 수 있습니까?


NSLocale 현재 사용되는 지역 설정에 대한 설정일 뿐이며 현재 거주하고있는 실제 국가를 의미하지는 않습니다.

CLLocationManager현재 위치를 가져 CLGeocoder오고 역 지오 코딩을 수행하는 데 사용 합니다 . 거기에서 국가 이름을 얻을 수 있습니다.


NSString *countryCode = [[NSLocale currentLocale] objectForKey: NSLocaleCountryCode];

"US"(미국), "ES"(스페인) 등과 같은 식별자를 받게됩니다.


에서 스위프트 3 :

let countryCode = NSLocale.current.regionCode

에서 스위프트 2.2 :

let countryCode = NSLocale.currentLocale().objectForKey(NSLocaleCountryCode) as String

CLLocationManager를 기반으로하는 솔루션과 비교할 때이 접근 방식에는 장단점이 있습니다. 주된 단점은 사용자가 장치를 다르게 구성하는 경우 장치가 물리적으로있는 위치임을 보장하지 않는다는 것입니다. 그러나 이것은 사용자가 정신적 / 문화적으로 어느 국가와 조화를 이루고 있는지 보여주기 때문에 프로로 볼 수도 있습니다. 예를 들어 휴가를 떠나 해외에 가면 로케일은 여전히 ​​제 모국으로 설정됩니다. 그러나 꽤 큰 장점은이 API가 CLLocationManager처럼 사용자 권한을 필요로하지 않는다는 것입니다. 따라서 사용자 위치를 사용할 수있는 권한을 아직 얻지 않았고 사용자 얼굴에 팝업 대화 상자를 던지는 것을 정당화 할 수없는 경우 (또는 이미 해당 팝업을 거부했고 대체가 필요합니다) 이것은 아마도 API 일 것입니다. 사용하고 싶습니다. 이에 대한 몇 가지 일반적인 사용 사례는 개인화 (예 :


@Denis의 대답은 좋습니다. 여기에 그의 대답을 실제로 적용하는 코드가 있습니다. 이것은 CLLocationManagerDelegate프로토콜 을 따르도록 설정 한 사용자 정의 클래스 용입니다 . 약간 단순화되었지만 (예를 들어 위치 관리자가 여러 위치를 반환하는 경우 첫 번째 위치 만 사용) 사람들에게 적절한 시작을 제공해야합니다.

- (id) init //designated initializer
{
    if (self)
    {
        self.locationManager = [[CLLocationManager alloc] init];
        self.geocoder = [[CLGeocoder alloc] init];
        self.locationManager.delegate = self;
        [self.locationManager startMonitoringSignificantLocationChanges];
    }
    return self;
}

- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations
{
    if (locations == nil)
        return;

    self.currentLocation = [locations objectAtIndex:0];
    [self.geocoder reverseGeocodeLocation:self.currentLocation completionHandler:^(NSArray *placemarks, NSError *error)
    {
        if (placemarks == nil)
            return;

        self.currentLocPlacemark = [placemarks objectAtIndex:0];
        NSLog(@"Current country: %@", [self.currentLocPlacemark country]);
        NSLog(@"Current country code: %@", [self.currentLocPlacemark ISOcountryCode]);
    }];
}

다음은 Swift 3 솔루션 을 위해 @Denis 와 @Matt의 답변입니다 .

import UIKit
import CoreLocation

class ViewController: UIViewController, CLLocationManagerDelegate {

    let locationManager = CLLocationManager()
    let geoCoder = CLGeocoder()

    override func viewDidLoad() {
        super.viewDidLoad()

        locationManager.requestAlwaysAuthorization()
        if CLLocationManager.locationServicesEnabled() {
            locationManager.delegate = self
            locationManager.startMonitoringSignificantLocationChanges()
        }
    }

    func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
        guard let currentLocation = locations.first else { return }

        geoCoder.reverseGeocodeLocation(currentLocation) { (placemarks, error) in
            guard let currentLocPlacemark = placemarks?.first else { return }
            print(currentLocPlacemark.country ?? "No country found")
            print(currentLocPlacemark.isoCountryCode ?? "No country code found")
        }
    }
}

설정된 잊지 마세요 NSLocationAlwaysUsageDescriptionNSLocationWhenInUseUsageDescription에가 Info.plist아니라!


여기에 아마도 지나치게 회로적인 방법이 있습니다. 다른 솔루션은 수동 설정 (NSLocale) 또는 거부 할 수있는 위치 서비스 사용 권한 요청 (CLLocationManager)을 기반으로하므로 단점이 있습니다.

You can get the current country based on the local timezone. My app is interfacing with a server running Python with pytz installed, and that module provides a dictionary of country codes to timezone strings. I only really need to have the server know the country so I don't have to set it up entirely on iOS. On the Python side:

>>> import pytz
>>> for country, timezones in pytz.country_timezones.items():
...     print country, timezones
... 
BD ['Asia/Dhaka']
BE ['Europe/Brussels']
BF ['Africa/Ouagadougou']
BG ['Europe/Sofia']
BA ['Europe/Sarajevo']
BB ['America/Barbados']
WF ['Pacific/Wallis']
...

On the iOS side:

NSTimeZone *tz = [NSTimeZone localTimeZone];
DLog(@"Local timezone: %@", tz.name); // prints "America/Los_Angeles"

I have my server send in the local timezone name and look it up in the pytz country_timezones dictionary.

If you make an iOS version of the dictionary available in pytz or some other source, you can use it to immediately look up the country code without the help of a server, based on timezone settings, which are often up to date.

I may be misunderstanding NSLocale though. Does it give you the country code through regional formatting preferences or timezone settings? If the latter, then this is just a more complicated way of getting the same result...


NSLocale *countryLocale = [NSLocale currentLocale];  
NSString *countryCode = [countryLocale objectForKey:NSLocaleCountryCode];
NSString *country = [countryLocale displayNameForKey:NSLocaleCountryCode value:countryCode];
NSLog(@"Country Locale:%@  Code:%@ Name:%@", countryLocale, countryCode, country);
//Country Locale:<__NSCFLocale: 0x7fd4b343ed40>  Code:US   Name:United States

For Swift 3 it's even simpler:

let countryCode = Locale.current.regionCode

You can get NSTimeZone from CLLocation: https://github.com/Alterplay/APTimeZones and works locally.


If you are only interested in telephone devices, then the technique mentioned here might be useful to you: Determine iPhone user's country


Here's a quick loop in Swift 3 that returns a complete list of country codes.

let countryCode = NSLocale.isoCountryCodes
    for country in countryCode {
        print(country)
    }

@Rob

let locale = Locale.current
let code = (locale as NSLocale).object(forKey: NSLocale.Key.countryCode) as! String?

using these code you will get your region country code and if you didn't get still then change it just go in Phone setting->general->language & region and set your region you want


Swift 4.0 code for getting the Country name as per region set:

    let countryLocale = NSLocale.current
    let countryCode = countryLocale.regionCode
    let country = (countryLocale as NSLocale).displayName(forKey: NSLocale.Key.countryCode, value: countryCode)
    print(countryCode, country)

prints: Optional("NG") Optional("Nigeria"). //for nigeria region set

참고URL : https://stackoverflow.com/questions/8534496/get-device-location-only-country-in-ios

반응형