[英]IOS Get User current country reliably
在我的 iOS 應用程序中,我需要獲取用戶當前所在的國家/地區。
我知道我可以使用CLLocation
來檢索位置,然后reverseGeocodeLocation
來獲取國家,但如果用戶不授權我的應用程序獲取他的位置,它將無法正常工作。 我可以使用(Locale.current as NSLocale).object(forKey: NSLocale.Key.countryCode)
; 但我想知道 countryCode 是在用戶旅行時更改還是僅在他手動更改設置時更改?
是否可以從當前的運營商處檢索此信息?
您可以使用此運營商找到國家代碼
CTTelephonyNetworkInfo *netInfo = [[CTTelephonyNetworkInfo alloc] init];
CTCarrier *carrier = [netInfo subscriberCellularProvider];
NSString *mcc = [carrier mobileCountryCode];
我設法使用以下方法在不要求位置權限的情況下到達該國家:
import MapKit
class CountryDectectorViewController: UIViewController {
var didDetectCountryCode: ((String?) -> Void)?
override func viewDidLoad() {
super.viewDidLoad()
// Map view setup
let mapView = MKMapView()
view.addSubview(mapView)
mapView.translatesAutoresizingMaskIntoConstraints = false
NSLayoutConstraint.activate([
mapView.topAnchor.constraint(equalTo: view.topAnchor),
mapView.bottomAnchor.constraint(equalTo: view.bottomAnchor),
mapView.leadingAnchor.constraint(equalTo: view.leadingAnchor),
mapView.trailingAnchor.constraint(equalTo: view.trailingAnchor)
])
mapView.layoutIfNeeded()
// Reverse geocoding map region center
let location = CLLocation(
latitude: mapView.region.center.latitude,
longitude: mapView.region.center.longitude
)
CLGeocoder().reverseGeocodeLocation(location) { placemarks, _ in
self.didDetectCountryCode?(placemarks?.first?.isoCountryCode)
}
}
}
然后可以使用以下方法獲得 ISO 國家代碼:
let controller = CountryDectectorViewController()
controller.loadViewIfNeeded()
controller.didDetectCountryCode = { countryCode in
print(countryCode)
}
一些上下文
我意識到 UIKit 已經擁有此信息,因為每次顯示MKMapView
時,該區域都會自動設置為適合當前用戶的國家/地區。 使用這個假設,我需要找到一個解決方案來加載 map 而不顯示它,然后對中心坐標進行反向地理編碼以識別國家。
考慮到我發現的以下限制,我實施了這個解決方案:
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.