iT邦幫忙

2018 iT 邦幫忙鐵人賽
0
Software Development

Swift 學習目標 -- 30 天送審第一支APP系列 第 32

請求定位權限及取得目前位置

為了取得 iPhone 裝置使用者的當前位置,我們首先必須先套用 Apple 的 CoreLocation 這個 library。

import CoreLocation

///並且對主要的 ViewController 進行 CLLocationManagerDelegate 的 subclass
ViewController: UIViewController, CLLocationManagerDelegate {

}

接著創造一個 locationManager

let locationManager = CLLocationManager()

override func viewDidLoad() {
        super.viewDidLoad()
        
        //TODO:Set up the location manager here.
        locationManager.delegate = self  //宣告自己 (current VC)為 locationManager 的代理
        locationManager.desiredAccuracy = kCLLocationAccuracyHundredMeters //定位所在地的精確程度(一般來說,精準程度越高,定位時間越長,所耗費的電力也因此更多)
        //to ask the user for location
        locationManager.requestWhenInUseAuthorization()  //for not destroying the user's battery
        locationManager.startUpdatingLocation() //this method will start navigating the location. And once this is done, it will send a msg to this ViewController
                
    }

接著,為了使請求定位權限的跳出視窗能夠順利在一打開 APP 時出現,我們必須回到 info.plist,添加這個彈出視窗的描述:

https://ithelp.ithome.com.tw/upload/images/20180126/20107694mIiYL56tCI.png

定義及管理定位方式:

定義定位方式:
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
//由於我們的 "startUpdatingLocation()" 會回傳一個陣列的 CLLocation ,而最後回傳的會是最接近於我們當前位置的 CLLocation 。 因此我們要娶的就是這個 CLLocation
    let location = locations[locations.count - 1]  //the method "startUpdatingLocation()" is gonna grab a set of locations that are getting more & more accurate. So we'd want the last location in this array
    //簡單檢查一下取得的值
     if location.horizontalAccuracy > 0 {  //this line will check if the location is available
     // 由於定位功能十分耗電,我們既然已經取得了位置,就該速速把它關掉
       locationManager.stopUpdatingLocation()
        print("latitude: \(location.coordinate.latitude), longtitude: \(location.coordinate.longitude)")            
        }
}

以及定義錯誤處理方式:

func locationManager(_ manager: CLLocationManager, didFailWithError error: Error) {
        print(error)
        cityLabel.text = "Location unavailable"
 }

上一篇
DAY 31 : 上傳圖片的 Button 寫法
下一篇
Notification 方法實作不同 View Controller 之間傳值
系列文
Swift 學習目標 -- 30 天送審第一支APP33
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

1 則留言

0
陳董 Don
iT邦新手 5 級 ‧ 2018-01-27 10:57:19

哇~~~持續發文中!

我要留言

立即登入留言