Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save aataraxiaa/25f3f5d1a41e28a4b558c97fe17b97df to your computer and use it in GitHub Desktop.
Save aataraxiaa/25f3f5d1a41e28a4b558c97fe17b97df to your computer and use it in GitHub Desktop.
import SwiftUI
import MapKit
// Main view
struct ContentView: View {
// Provides an annotation after some delay (asynchronously)
@ObservedObject var asynchronousAnnotationMaker = AsynchronousAnnotationMaker()
var body: some View {
MapView(annotation: asynchronousAnnotationMaker.annotation).edgesIgnoringSafeArea(.all)
.onAppear {
self.asynchronousAnnotationMaker.makeAnnotation()
}
}
}
// Map view. Displays a map and a single map annotation.
struct MapView: UIViewRepresentable {
var annotation: MKAnnotation?
private let map = MKMapView()
func makeUIView(context: Context) -> MKMapView {
return map
}
func updateUIView(_ mapView: MKMapView, context: Context) {
refreshAnnotation()
}
private func refreshAnnotation() {
map.removeAnnotations(map.annotations)
if let annotation = annotation {
map.addAnnotation(annotation)
}
}
}
// Provides a map annotation afte some delay. A timer is used to simulate a delay which may occur due to a network request
class AsynchronousAnnotationMaker: ObservableObject {
@Published var annotation: MKAnnotation?
func makeAnnotation() {
Timer.scheduledTimer(withTimeInterval: 2, repeats: false) { timer in
self.annotation = MKPlacemark(coordinate: CLLocationCoordinate2D(latitude: 53.345589, longitude: -6.286951), addressDictionary: ["City":"Dublin", "Country":"Ireland"])
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment