Swift version: 5.6
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?
SPONSORED Join a FREE crash course for mid/senior iOS devs who want to achieve an expert level of technical and practical skills – it’s the fast track to being a complete senior developer! Hurry up because it'll be available only until April 28th.
Sponsor Hacking with Swift and reach the world's largest Swift community!
Available from iOS 2.0
This is part of the Swift Knowledge Base, a free, searchable collection of solutions for common iOS questions.
Link copied to your pasteboard.