使用swiftUI加入要求定位的功能
這邊使用CLLocationManager來完成,步驟如下:
- 新增class,import CoreLoacation框架
import CoreLocation
class LocationVieModel: NSObject, ObservableObject, CLLocationManagerDelegate {
@Published var authorizationStatus: CLAuthorizationStatus //權限狀態
private let locationManager: CLLocationManager
override init() {
locationManager = CLLocationManager()
authorizationStatus = locationManager.authorizationStatus
super.init()
locationManager.delegate = self
locationManager.desiredAccuracy = kCLLocationAccuracyBest
locationManager.startUpdatingLocation()
}
}
2. 在欲做取得定位的View加入以下code
@StateObject var locationViewModel = LocationVieModel()
var body: some View{
VStack{
locationViewModel.requestPermission()
}
}
3. 回到LocationViewModel,加入以下function
func requestPermission() {
locationManager.requestWhenInUseAuthorization()
}
func locationManagerDidChangeAuthorization(_ manager: CLLocationManager) {
authorizationStatus = manager.authorizationStatus
}
4.即可使用模擬器看到位置請求🥹
⚠️模擬器可以自行設定座標,操作如下:
打開模擬器->點選Features->選擇Location->點選Custom Location
5. 如果想讀取位置的座標,在LocationViewModel中加入以下
@Published var lastSeenLocation: CLLocation?
@Published var currentPlaceark: CLPlacemark?
// ...
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
lastSeenLocation = locations.first
}
func fetchCountryAndCity(for location: CLLocation?) {
guard let location = location else { return }
let geocoder = CLGeocoder()
geocoder.reverseGeocodeLocation(location) { (placemarks, error) in
self.currentPlaceark = placemarks?.first
}
}
6. 在要讀取的View中加入
var coordinate: CLLocationCoordinate2D? {
locationViewModel.lastSeenLocation?.coordinate
}
var body: some View{
VStack{
Text(String(coordinate?.longitude ?? 0))
Text(String(coordinate?.latitude ?? 0))
}
}
參考網站
https://www.andyibanez.com/posts/using-corelocation-with-swiftui/