iT邦幫忙

2019 iT 邦幫忙鐵人賽

DAY 21
0
自我挑戰組

IOS app開發介紹系列 第 22

IOS app開發介紹 - location service (2)

  • 分享至 

  • xImage
  •  

前一篇提到向系統要求定位權限,這一篇要講的是"獲取目前的地址與經緯度"


我們分為兩個步驟來看:

1.獲取經緯度
2.經緯度轉換成地址


1.獲取經緯度

呼叫CLLocationManager提供的method startUpdatingLocation(),我們就能夠在CLLocationManagerDelegate的system callback didUpdateLocations中得到經緯度.
特別注意的是locationManager允許我們去設定定位的精準度,共有以下幾項:
public let kCLLocationAccuracyBestForNavigation: CLLocationAccuracy
public let kCLLocationAccuracyBest: CLLocationAccuracy
public let kCLLocationAccuracyNearestTenMeters: CLLocationAccuracy
public let kCLLocationAccuracyHundredMeters: CLLocationAccuracy
public let kCLLocationAccuracyKilometer: CLLocationAccuracy
public let kCLLocationAccuracyThreeKilometers: CLLocationAccuracy

如果我們需要的定位不用那麼精準的話,其實可以選低一點的精準度來減少獲取經緯度的時間

(a) startUpdatingLocation()

        if CLLocationManager.locationServicesEnabled() {
            locationManager.desiredAccuracy = kCLLocationAccuracyNearestTenMeters
            locationManager.startUpdatingLocation()
        }

(b) didUpdateLocations system callback

func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
    guard let locValue: CLLocationCoordinate2D = manager.location?.coordinate else { return }
    print("locations = \(locValue.latitude) \(locValue.longitude)")
      self.locationManager.stopUpdatingLocation()
    }

Note: 我們在didUpdateLocations這個system callback中加入**self.locationManager.stopUpdatingLocation()**來停止update location,否則ios會持續地為我們獲取經緯度,在這裡因為我們只需要一組,所以獲取後,就停止update location


2.經緯度轉換成地址

前一步驟拿到經緯度後,我們利用CLGeocoder提供的reverseGeocodeLocation來把經緯度轉換成地址

    let ceo: CLGeocoder = CLGeocoder()
    let loc: CLLocation = CLLocation(latitude: lat, longitude: lon)
    
    let locale = Locale(identifier: "zh_TW")
    if #available(iOS 11.0, *) {
        ceo.reverseGeocodeLocation(loc, preferredLocale: locale) {
            (placemarks, error) in
            if error == nil {
                let pm = placemarks! as [CLPlacemark]
                if pm.count > 0 {
                    let pm = placemarks![0]
                    print(pm.country)
                    print(pm.locality)
                    print(pm.subLocality)
                    print(pm.thoroughfare)
                    print(pm.postalCode)
                    print(pm.subThoroughfare)
                }
            }
        }
    } 
    

Note1: 在上面我們再把經緯度轉換成地址前,我們還設定locale來決定轉換後地址的語系
Note2: ios 11.0以前要決定轉換後地址的語系,需要透過hard-code string key來實現,詳細code如下:

         UserDefaults.standard.set(["zh_TW"], forKey: "AppleLanguages")
            ceo.reverseGeocodeLocation(loc, completionHandler:
                {(placemarks, error) in
                    UserDefaults.standard.removeObject(forKey: "AppleLanguages")
                    if error == nil {
                        let pm = placemarks! as [CLPlacemark]
                        if pm.count > 0 {
                            let pm = placemarks![0]
                            print(pm.country)
                            print(pm.locality)
                            print(pm.subLocality)
                            print(pm.thoroughfare)
                            print(pm.postalCode)
                            print(pm.subThoroughfare)
                        }
                    }
            })

完整專案在以下連結:
https://github.com/tgnivekucn/GetLocation2

下一篇我們將講解 給予地址轉換經緯度與郵遞區號 的方法


ref: https://www.jianshu.com/p/022a5fa58fdb


上一篇
IOS app開發介紹 - location service
系列文
IOS app開發介紹22
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言