System Frameworks

Article · 2:00

Push notifications, location, maps and on-device machine learning - and the permission each one needs.

What separates an app from a website in a wrapper is the device. Four frameworks cover most of it.

Push notifications need a capability enabled in Xcode, a request for authorisation at a moment the reader understands why, and a device token sent to your server. Remote notifications only arrive on a real device - never in the Simulator - which surprises people for an afternoon. CoreLocation asks for permission in two steps: when-in-use first, and only later, with a reason, always. Ask for always up front and most people decline. MapKit now has a SwiftUI Map view, so annotations and camera position are ordinary SwiftUI state. CoreML runs a trained model on the device, which means no network, no latency and no data leaving the phone; Vision wraps it for image work in a few lines.

Every one of these needs a usage-description string in your Info.plist, written in plain language. The app crashes immediately without it - deliberately, so you cannot ship a permission request with no explanation - and App Review reads the strings. "We use your location to show nearby stores" passes. "Required for app functionality" does not.

import SwiftUI
import MapKit
import CoreLocation
import UserNotifications

// Location: ask for when-in-use, at a moment with visible purpose.
@Observable
final class LocationModel: NSObject, CLLocationManagerDelegate {
    private let manager = CLLocationManager()
    var coordinate: CLLocationCoordinate2D?

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

    func request() { manager.requestWhenInUseAuthorization() }

    func locationManagerDidChangeAuthorization(_ manager: CLLocationManager) {
        guard manager.authorizationStatus == .authorizedWhenInUse else { return }
        manager.startUpdatingLocation()
    }

    func locationManager(_ m: CLLocationManager, didUpdateLocations locs: [CLLocation]) {
        coordinate = locs.last?.coordinate
    }
}

struct NearbyScreen: View {
    @State private var location = LocationModel()
    @State private var camera: MapCameraPosition = .automatic

    var body: some View {
        Map(position: $camera) {
            if let here = location.coordinate {
                Marker("You", coordinate: here)
            }
        }
        .task {
            location.request()
            // Notifications: ask, then register for a device token.
            _ = try? await UNUserNotificationCenter.current()
                .requestAuthorization(options: [.alert, .sound, .badge])
        }
    }
}