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

80 lines
2.6 KiB
Swift
Raw Normal View History

2024-07-04 11:45:39 +00:00
import CoreLocation
2024-07-02 09:56:27 +00:00
import MapKit
import SwiftUI
struct AttachmentLocationPickerView: View {
2024-07-04 13:40:32 +00:00
@StateObject var locationManager = LocationManager()
@State private var region = MKCoordinateRegion()
@State var userInteracted: Bool = false
2024-07-02 09:56:27 +00:00
var body: some View {
2024-07-04 13:40:32 +00:00
Map(
coordinateRegion: $region,
interactionModes: .all,
showsUserLocation: false,
userTrackingMode: .none
)
.onAppear {
locationManager.start()
}
.onDisappear {
locationManager.stop()
}
.onChange(of: locationManager.region) { region in
if !userInteracted {
let currentLoc = CLLocation(latitude: self.region.center.latitude, longitude: self.region.center.longitude)
let newLoc = CLLocation(latitude: region.center.latitude, longitude: region.center.longitude)
if newLoc.distance(from: currentLoc) > 10 {
DispatchQueue.main.async {
withAnimation {
self.region = region
2024-07-04 12:55:47 +00:00
}
}
}
}
2024-07-04 13:40:32 +00:00
}
.overlay {
Image(systemName: "mappin")
.font(.title2)
.foregroundColor(.Material.Elements.active)
}
.onChange(of: region) { region in
print("Region changed: \(region.center)")
}
2024-07-04 11:45:39 +00:00
}
}
class LocationManager: NSObject, ObservableObject, CLLocationManagerDelegate {
2024-07-04 13:40:32 +00:00
@Published var region = MKCoordinateRegion()
2024-07-04 11:45:39 +00:00
private let locationManager = CLLocationManager()
override init() {
super.init()
locationManager.delegate = self
2024-07-04 13:40:32 +00:00
locationManager.desiredAccuracy = kCLLocationAccuracyBest
2024-07-04 11:45:39 +00:00
}
func start() {
locationManager.requestWhenInUseAuthorization()
locationManager.startUpdatingLocation()
}
2024-07-04 13:40:32 +00:00
func stop() {
locationManager.stopUpdatingLocation()
2024-07-02 09:56:27 +00:00
}
2024-07-04 11:54:09 +00:00
2024-07-04 13:40:32 +00:00
func locationManager(_: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
guard let location = locations.last else { return }
region = MKCoordinateRegion(center: location.coordinate, span: MKCoordinateSpan(latitudeDelta: 0.001, longitudeDelta: 0.001))
2024-07-04 11:54:09 +00:00
}
2024-07-02 09:56:27 +00:00
}
2024-07-04 13:40:32 +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
2024-07-02 09:56:27 +00:00
}
}