← All repositories

reportage

A life-logging app for iPhone

git clone https://code.inqk.net/reportage.git


Reportage/Services/FirstLaunch.swift (3511B)

1import CoreLocation
2import UserNotifications
3
4/// The permissions Reportage asks for when it's first opened: location,
5/// notifications, then Health, each after the welcome screen has said what
6/// it's for.
7///
8/// Every report records where it was made, so location is asked for at
9/// once rather than when the first report is made. It's asked for as
10/// 'Always', which iOS shows as the usual 'While Using' prompt: choosing
11/// that grants 'Always' provisionally, so Instant Report records location
12/// from a notification straight away, and iOS confirms it with the user
13/// later. Allowing notifications turns on random prompts, which are what
14/// they're for.
15enum FirstLaunch {
16    private static let key = "askedFirstLaunchPermissions"
17    private static let log = EventLog.shared.category("App")
18
19    /// Whether to welcome the user: the first time the app is opened, if
20    /// any permission is still undecided. Someone updating from a version
21    /// that asked later, with all of them decided, isn't welcomed. An install
22    /// welcomed before Health was asked for is welcomed once more for it.
23    @MainActor
24    static func isNeeded(defaults: UserDefaults = .standard) async -> Bool {
25        let health = await HealthAccess.needsAsking()
26        guard !defaults.bool(forKey: key) else { return health }
27        let notifications = await UNUserNotificationCenter.current().notificationSettings().authorizationStatus
28        guard CLLocationManager().authorizationStatus == .notDetermined || notifications == .notDetermined || health
29        else {
30            defaults.set(true, forKey: key)
31            return false
32        }
33        return true
34    }
35
36    /// Asks for each permission still undecided, one after the other, and
37    /// remembers that they've been asked for.
38    @MainActor
39    static func ask(defaults: UserDefaults = .standard) async {
40        await askForLocation()
41        await askForNotifications()
42        await HealthAccess.ask(defaults: defaults)
43        defaults.set(true, forKey: key)
44    }
45
46    /// Holds an 'Always' session until the prompt is answered, so the
47    /// notifications prompt doesn't come over it. Gives up after two
48    /// minutes so a prompt left on screen can't hold up the next one.
49    private static func askForLocation() async {
50        guard CLLocationManager().authorizationStatus == .notDetermined else { return }
51        let session = CLServiceSession(authorization: .always)
52        defer { session.invalidate() }
53        _ = await withTimeout(.seconds(120)) { () async -> Bool? in
54            do {
55                for try await _ in session.diagnostics
56                where CLLocationManager().authorizationStatus != .notDetermined {
57                    return true
58                }
59            } catch {}
60            return nil
61        }
62        log.info("Asked for location: status \(CLLocationManager().authorizationStatus.rawValue)")
63    }
64
65    private static func askForNotifications() async {
66        let center = UNUserNotificationCenter.current()
67        guard await center.notificationSettings().authorizationStatus == .notDetermined else { return }
68        let granted = (try? await center.requestAuthorization(options: [.alert, .sound])) ?? false
69        log.info("Asked for notifications: \(granted ? "allowed" : "not allowed")")
70        guard granted else { return }
71        var settings = PromptSettings.load()
72        settings.isEnabled = true
73        settings.save()
74        await PromptScheduler().refresh()
75    }
76}