Skip to main content

Day 78

About 2 minSwiftcrashcoursepaul-hudsonswiftswiftuihacking-with-swiftxcodeappstore

Day 78 ๊ด€๋ จ


100 Days of SwiftUI - Day 78

Time for MapKit

Time for MapKit

Yesterday you built a new app that imports photos from the userโ€™s library, and hopefully youโ€™re pleased with the finished product โ€“ or at least making great progress towards the finished product.

But your boss has come in and demanded a new feature: when youโ€™re viewing a picture that was imported, you should show a map with a pin that marks where they were when that picture was added. It might be on the same screen side by side with the photo, it might be shown or hidden using a segmented control, or perhaps itโ€™s on a different screen โ€“ itโ€™s down to you. Regardless, you know how to drop pins, and you also know how to use the center coordinate of map views, so the only thing left to figure out is how to get the userโ€™s location to save alongside their text and image.

Although I do want you to push your skills, Iโ€™m not cruel. So, hereโ€™s a class that fetches the userโ€™s location:

import CoreLocation

class LocationFetcher: NSObject, CLLocationManagerDelegate {
    let manager = CLLocationManager()
    var lastKnownLocation: CLLocationCoordinate2D?

    override init() {
        super.init()
        manager.delegate = self
    }

    func start() {
        manager.requestWhenInUseAuthorization()
        manager.startUpdatingLocation()
    }

    func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
        lastKnownLocation = locations.first?.coordinate
    }
}

To use that, start by adding a new key in the Info tab for your app's target, just like we did when we wanted Face ID permission. This key is called โ€œPrivacy - Location When In Use Usage Descriptionโ€, then give it some sort of value explaining to the user why you need their location.

Now you can use it inside SwiftUI view like this:

struct ContentView: View {
    let locationFetcher = LocationFetcher()

    var body: some View {
        VStack {
            Button("Start Tracking Location") {
                locationFetcher.start()
            }

            Button("Read Location") {
                if let location = locationFetcher.lastKnownLocation {
                    print("Your location is \(location)")
                } else {
                    print("Your location is unknown")
                }
            }
        }
    }
}

If youโ€™re using the simulator rather than a real device, you can fake a location by going to the Debug menu and choosing [Location] > [Apple].

And now itโ€™s over to you: can you add the feature your boss wants, and bring MapKit and SwiftUI together in a single app?


์ด์ฐฌํฌ (MarkiiimarK)
Never Stop Learning.