[iOS] NSLocale的簡介

SC Tuan
SC Tuan
Aug 28, 2017 · 2 min read

剛剛在研究NSLocale的用法,這邊紀錄一下。

基本上NSLocale表示某地區習慣使用的符號與文化,如果你呼叫currentLocale,那你會得到你手機目前設定的地區。

手機內進入設定App>一般>語言與地區>地區,這邊可以選擇你要使用的地區,currentLocale反映的是你在這邊設定的值,而非你目前真正所在的地方。

NSLocale *currentLocale = NSLocale.currentLocale;

你在currentLocale可以得到什麼呢?以台灣為例,以下列出一些值:

NSLocale.currentLocale.languageCode
// zh
NSLocale.currentLocale.localeIdentifier
// zh_TW
NSLocale.currentLocale.calendarIdentifier
// gregorian
NSLocale.currentLocale.collatorIdentifier
// zh-Hant-TW
NSLocale.currentLocale.decimalSeparator
// .
NSLocale.currentLocale.currencyCode
// TWD
NSLocale.currentLocale.currencySymbol
// $
NSLocale.currentLocale.localeIdentifier
// zh_TW

大概是這些。

如果你實際上想要得到你手機目前所在的國家,你要用CoreLocation裡面的startUpdatingLocation去偵測目前位置,然後用CLGeocoder的reverseGeocodeLocation方法去得到countryCode。

做法是透過reverseGeocodeLocation的completion裡面帶的CLPlacemark的ISOcountryCode就可以得到國家的縮寫,台灣是TW。

只是,NSLocale.currentLocale裡面沒有手機目前所設定地區的ISOcountryCode,所以你也無法透過CLPlacemark得到的真實國家去初始化你要用的NSLocale實例來用。

)
SC Tuan

SC Tuan

iOS developer😘 / Web developer🤪/ anymore? 😎

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade