another.im-ios/ConversationsClassic/View/Screens/Attachments/AttachmentLocationPickerView.swift

91 lines
2.4 KiB
Swift
Raw Normal View History

2024-07-02 09:56:27 +00:00
import MapKit
import SwiftUI
struct AttachmentLocationPickerView: View {
2024-07-05 08:36:35 +00:00
@StateObject var locationManager = LocationManager()
2024-07-04 14:25:25 +00:00
@State var region = MKCoordinateRegion()
2024-07-02 09:56:27 +00:00
var body: some View {
2024-07-05 08:36:35 +00:00
ZStack {
MapView(region: $region)
}
.onAppear {
locationManager.start()
}
.onChange(of: locationManager.region) { region in
self.region = region
}
}
}
struct MapView: UIViewRepresentable {
@Binding var region: MKCoordinateRegion
func makeUIView(context: Context) -> MKMapView {
let mapView = MKMapView()
mapView.delegate = context.coordinator
mapView.showsUserLocation = true
mapView.userTrackingMode = .none
return mapView
}
func updateUIView(_ uiView: MKMapView, context _: Context) {
if uiView.region != region {
uiView.setRegion(region, animated: true)
}
}
func makeCoordinator() -> Coordinator {
Coordinator(self)
}
class Coordinator: NSObject, MKMapViewDelegate {
var parent: MapView
init(_ parent: MapView) {
self.parent = parent
}
}
}
class LocationManager: NSObject, ObservableObject {
private let locationManager = CLLocationManager()
@Published var region: MKCoordinateRegion
override init() {
region = MKCoordinateRegion()
super.init()
locationManager.delegate = self
locationManager.desiredAccuracy = kCLLocationAccuracyBest
}
func start() {
locationManager.requestWhenInUseAuthorization()
locationManager.startUpdatingLocation()
}
func stop() {
locationManager.stopUpdatingLocation()
}
}
extension LocationManager: CLLocationManagerDelegate {
func locationManager(_: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
if let loc = locations.first {
region = MKCoordinateRegion(
center: loc.coordinate,
span: MKCoordinateSpan(latitudeDelta: 0.002, longitudeDelta: 0.002)
2024-07-04 15:01:30 +00:00
)
2024-07-04 13:40:32 +00:00
}
2024-07-02 09:56:27 +00:00
}
}
2024-07-05 08:36:35 +00:00
extension MKCoordinateRegion: Equatable {
public static func == (lhs: MKCoordinateRegion, rhs: MKCoordinateRegion) -> Bool {
lhs.center.latitude == rhs.center.latitude &&
lhs.center.longitude == rhs.center.longitude &&
lhs.span.latitudeDelta == rhs.span.latitudeDelta &&
lhs.span.longitudeDelta == rhs.span.longitudeDelta
}
}