釣魚術
swift
swiftui
CoreLocation
Map
final class FishingLocationModel: NSObject, ObservableObject, CLLocationManagerDelegate
@Published
明天再來談final class FishingLocationModel: NSObject, ObservableObject, CLLocationManagerDelegate {
@Published var region = MKCoordinateRegion(
center: CLLocationCoordinate2D(latitude: 25.1125, longitude: 121.4582),
span: MKCoordinateSpan(latitudeDelta: 0.008, longitudeDelta: 0.008))
let locationManager = CLLocationManager()
// 先宣告 locationManager 是 CLLocationManager() 的 instance
override init() { // 改寫 init 函式
super.init() // 先繼承原 init()
locationManager.delegate = self //再加上 locationManager.delegate
}
// 弄出一條讓按鈕按按下事件呼叫的函式
func requestAllowOnceLocationPermission() {
locationManager.requestLocation()
}
requestLocation()
被呼叫後,從 Handler 去收取結果。 func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
guard let latestLocation = locations.first else {
return
}
DispatchQueue.main.async {
self.region = MKCoordinateRegion(
center: latestLocation.coordinate,
span: MKCoordinateSpan(latitudeDelta: 0.01, longitudeDelta: 0.01))
print("Region --> \(self.region)")
}
}
func locationManager(_ manager: CLLocationManager, didFailWithError error: Error) {
print(error.localizedDescription)
}
}