简体   繁体   中英

Can you determine what country your user is in from an iOS app?

I'm trying to determine whether to use imperial or metric units automatically before asking the user to enable location services. I know that you can't get precise data but all I really need is United States or not. Can you determine what store it was downloaded from or use IP address or anything like that?

You could use the device's locale to achieve this...

Obj-C

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

Swift

let locale = NSLocale.currentLocale()
let countryCode = locale.objectForKey(NSLocaleCountryCode)

Country codes are in the format US (United States), FR (France), etc...

Note that the locale is based on the user's device settings and not necessarily the current physical location of the device.

You're probably looking for NSLocale:

    let theLocale = NSLocale.autoupdatingCurrentLocale()
    print(theLocale.objectForKey(NSLocaleMeasurementSystem))
    print(theLocale.objectForKey(NSLocaleUsesMetricSystem))

Look at the NSLocale class reference for more options.

Swift 3

NSLocale.current
NSLocale.Key.countryCode

Yes, annoyingly renamed again, don't you have more important stuff to attend Swift team???

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM