Search code examples
xcodeswiftuipreview

SwiftUI Preview Macro: how to provide private state property value for preview use


From Xcode 15, it involves preview macro.

I created an simple app with MapKit to learn it.

struct LocationDetailsView: View {
    @Binding var mapSelection: MKMapItem?
    @Binding var show: Bool
    @State private var lookAroundScene: MKLookAroundScene?
    @Binding var getDirections: Bool
    
    var body: some View {
        VStack {
            HStack {
                VStack(alignment: .leading) {
                    Text(mapSelection?.placemark.name ?? "")
                        .font(.title2)
                        .fontWeight(.semibold)
                    
                    Text(mapSelection?.placemark.title ?? "")
                        .font(.footnote)
                        .foregroundStyle(.gray)
                        .lineLimit(2)
                        .padding(.trailing)
                }
                        
                Spacer()
                
                Button {
                    show.toggle()
                    mapSelection = nil
                } label: {
                    Image(systemName: "xmark.circle.fill")
                        .resizable()
                        .frame(width: 24, height: 24)
                        .foregroundStyle(.gray, Color(.systemGray5))
                }
            }
            .padding(.init(top: 40, leading: 20, bottom: 0, trailing: 20))
            
            if let scene = lookAroundScene {
                LookAroundPreview(initialScene: scene)
                    .frame(height: 200)
                    .cornerRadius(12)
                    .padding()
            } else {
                ContentUnavailableView("No preview available", systemImage: "eye.slash")
            }
            
            HStack(spacing: 24) {
                Button {
                    if let mapSelection {
                        mapSelection.openInMaps()
                    }
                } label: {
                    Text("Open in Maps")
                        .font(.headline)
                        .foregroundColor(.white)
                        .frame(width: 170, height: 48)
                        .background(.green)
                        .cornerRadius(12)
                }
                
                Button {
                    getDirections = true
                    show = false
                } label: {
                    Text("Get Directions")
                        .font(.headline)
                        .foregroundColor(.white)
                        .frame(width: 170, height: 48)
                        .background(.blue)
                        .cornerRadius(12)
                }
            }
            .padding(.horizontal)
        }
        .onAppear {
            print("DEBUG: Did call on appear")
            fetchLookAroundPreview()
        }
        .onChange(of: mapSelection) { oldValue, newValue in
            print("DEBUG: Did call on change")
            fetchLookAroundPreview()
        }
        .padding()
    }
}

extension LocationDetailsView {
    func fetchLookAroundPreview() {
        if let mapSelection {
            lookAroundScene = nil
            Task {
                let request = MKLookAroundSceneRequest(mapItem: mapSelection)
                lookAroundScene = try? await request.scene
                print("DEBUG: lookAroundScene \(lookAroundScene)")
            }
        }
    }
}

#Preview {
    LocationDetailsView(
        mapSelection: .constant(MKMapItem.forCurrentLocation()),
        show: .constant(true) ,
        getDirections: .constant(false)
    )
}

And in preview idk how to provide the lookAroundScene property value to it, please give me some advice. BTW, this lookAroundScene would show a image regarding current mapSelection, it is ideal if I could show it in the preview.

Update per Sweeper's answer

enter image description here


Solution

  • I don't think Previews have access to the current location, so MKLookAroundSceneRequest doesn't know where MKMapItem.forCurrentLocation() is.

    Since making your own dummy MKMapItem is a bit too much trouble for me, I'd suggest to just use the other initialiser of MKLookAroundSceneRequest that takes a coordinate.

    Rather than passing in the coordinate from #Preview, you can just detect whether you are in a preview. e.g. using Aleš Kocur's answer there:

    let request = !isPreview ? 
        MKLookAroundSceneRequest(mapItem: mapSelection) :
        MKLookAroundSceneRequest(coordinate: CLLocationCoordinate2D(latitude: 51.5069819, longitude: -0.0889239)) // somewhere in London
    

    You can still pass in a coordinate from #Preview { } if you want - e.g. adding an extra let to your view that stores which coordinate to use in a preview, or using an enum like this as the type for mapSelection:

    enum MapSelection {
        case mapItem(MKMapItem)
        case coordinate(CLLocationCoordinate2D)
    }
    

    But obviously that would involve changing a lot of your existing code.