I want to generate randomised MKLookAroundScene for my world exploration app (think geogussr functionality). How can i achieve that with MapKit? I have tried
struct LookAroundView: View { @State private var lookAroundScene: MKLookAroundScene? @State private var yOffset: CGFloat = 0 func generateRandomCoordinate() { let minLatitude = -90.0 let maxLatitude = 90.0 let minLongitude = -180.0 let maxLongitude = 180.0 let randomCoordinate = CLLocationCoordinate2D( latitude: Double.random(in: minLatitude...maxLatitude), longitude: Double.random(in: minLongitude...maxLongitude) ) checkLookAroundAvailability(coordinate: randomCoordinate) } func checkLookAroundAvailability(coordinate: CLLocationCoordinate2D) { Task { let request = MKLookAroundSceneRequest(coordinate: coordinate) if let scene = try? await request.scene { DispatchQueue.main.async { self.lookAroundScene = scene } } else { generateRandomCoordinate() } } } var body: some View { Group { if let scene = lookAroundScene { LookAroundPreview(initialScene: scene) } else { Button(action: { generateRandomCoordinate() }) { Text("Generate Random Coordinate") } .offset(y: yOffset) } } } }
but it didn't work. I put the yOffset change there to debug, and it seems that self.lookAroundScene = scene
never gets executed.
If there are any other options, please let me know!
Have you tried catching the error from your try await request.scene
? I have just finished a similar task and no issues. Perhaps also try using MainActor.run
so that you are not combining async/await with DispatchQueue? I've heard others having issues when mixing the two.
Task { do { let request = MKLookAroundSceneRequest(coordinate: coordinate) let scene = try await request.scene await MainActor.run { self.lookAroundScene = scene } } catch { print(error.localizedDescription) // This will help! generateRandomCoordinate() } }