Reportage/Services/FirstLaunch.swift (3511B)
1import CoreLocation
2import UserNotifications
3
4
5
6
7
8
9
10
11
12
13
14
15enum FirstLaunch {
16 private static let key = "askedFirstLaunchPermissions"
17 private static let log = EventLog.shared.category("App")
18
19
20
21
22
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
37
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
47
48
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}