BLACK FRIDAY: Save 50% on all my Swift books and bundles! >>

How to detect which country a user is in

Swift version: 5.10

Paul Hudson    @twostraws   

Being able to provide users with location-specific information immediately makes your app more useful, but asking for a precise location brings up a permission alert and might make them suspicious. Fortunately there's a coarse-grained way you can figure out a user's locate without asking for location permission: Locale.

A locale is a user's region setting on their device, and you can read it without asking for permission. For example, if the locale is en-US it means they speak English and are in the US; if it's fr-CA it means they speak French are in Canada. This is all wrapped up inside Locale and you can query various information from it, but for our simple purpose we're just going to ask what country the user is in:

let locale = Locale.current
print(locale.regionCode)

Now, there is a catch, but this is actually a bonus feature in my eyes: if a user travels abroad, their device will still be configured for their home country, so an American visiting France will still say "US".

Yes, that means you can't use it for location information, but actually it works out better for a lot of apps – for example, why would an American want to see distances in meters rather than miles just because they are traveling?

Save 50% in my WWDC sale.

SAVE 50% All our books and bundles are half price for Black Friday, so you can take your Swift knowledge further without spending big! Get the Swift Power Pack to build your iOS career faster, get the Swift Platform Pack to builds apps for macOS, watchOS, and beyond, or get the Swift Plus Pack to learn advanced design patterns, testing skills, and more.

Save 50% on all our books and bundles!

Available from iOS 2.0

Similar solutions…

About the Swift Knowledge Base

This is part of the Swift Knowledge Base, a free, searchable collection of solutions for common iOS questions.

BUY OUR BOOKS
Buy Pro Swift Buy Pro SwiftUI Buy Swift Design Patterns Buy Testing Swift Buy Hacking with iOS Buy Swift Coding Challenges Buy Swift on Sundays Volume One Buy Server-Side Swift Buy Advanced iOS Volume One Buy Advanced iOS Volume Two Buy Advanced iOS Volume Three Buy Hacking with watchOS Buy Hacking with tvOS Buy Hacking with macOS Buy Dive Into SpriteKit Buy Swift in Sixty Seconds Buy Objective-C for Swift Developers Buy Beyond Code

Was this page useful? Let us know!

Average rating: 4.2/5

 
Unknown user

You are not logged in

Log in or create account
 

Link copied to your pasteboard.