Search code examples
iosswiftswift-playgroundswift5.7

how to write a function that takes coordinate(lat - long) and take snapshot from desired location with lookaround.snapshotter in Swift?


I just started programming in Swift and I am a complete beginner. I wanted to write a function or class that, by receiving the coordinates, if there is a photo in MKLookAround.request, saves a photo of the desired location using MKLookAround.Snapshotter, but I don't know how to use the mapkit ready classes. I don't want to use swiftUI, I just want to save pictures for a number of coordinates from different places. enter image description here


Solution

  • You can create a MKLookAroundSceneRequest, grab its scene, and then supply that to MKLookAroundSnapshotter.

    func snapshotImage(for coordinate: CLLocationCoordinate2D) async throws -> UIImage {
        guard let scene = try await MKLookAroundSceneRequest(coordinate: coordinate).scene else {
            throw LookaroundError.unableToCreateScene
        }
        let options = MKLookAroundSnapshotter.Options()
        options.size = CGSize(width: 1000, height: 500)
        return try await MKLookAroundSnapshotter(scene: scene, options: options).snapshot.image
    }
    

    enter image description here

    That uses this Error object:

    enum LookaroundError: Error {
        case unableToCreateScene
    }
    

    For more information, see WWDC 2022 What’s new in MapKit or check out the use of MKLookAroundSnapshotter in their sample project.


    And if you want to write that to a file get either the PNG (pngData) or JPG (jpgData) representation and write it to a file:

    let image = try await snapshotImage(for: coordinate)
    let url = try FileManager.default
        .url(for: .applicationSupportDirectory, in: .userDomainMask, appropriateFor: nil, create: true)
        .appending(component: "test.png")
    try image.pngData()?.write(to: url)
    

    Or alternatively, you might want to present a user a UI whereby they can specify what they want to do with the image, via UIActivityViewController:

    let share = UIActivityViewController(activityItems: [image], applicationActivities: nil)
    self.present(share, animated: true)