krz/moonrise

Night-sky companion for iPhone, Apple Watch and Vision Pro: what's up tonight, the Moon, planets, launches and missions, and a Library of the solar system. SwiftUI app with a Cloudflare Workers backend. astronomy cloudflare-workers ios night-sky space swiftui visionos watchos

App/Sources/MoonriseApp.swift

70 lines · 3321 bytes

 1import SkyRenderer
 2import SwiftUI
 3import UIKit
 4import UserNotifications
 5import os
 6
 7let log = Logger(subsystem: "sh.krz.moonrise", category: "app")
 8
 9@main
10struct MoonriseApp: App {
11    @UIApplicationDelegateAdaptor(AppDelegate.self) var appDelegate
12    @AppStorage(SettingsKey.onboarded) private var onboarded = false
13    @AppStorage(SettingsKey.nightActive) private var nightActive = false
14    @State private var router = Router.shared
15    @Environment(\.scenePhase) private var scenePhase
16
17    var body: some Scene {
18        WindowGroup {
19            TabView(selection: $router.tab) {
20                Tab("Sky", systemImage: "sparkles", value: "sky") { SkyScreen() }
21                Tab("System", systemImage: "circle.circle", value: "system") { SystemScreen() }
22                Tab("Sun", systemImage: "sun.max", value: "sun") { SunScreen() }
23                Tab("News & launches", systemImage: "airplane.departure", value: "launches") { LaunchesScreen() }
24                Tab("Library", systemImage: "books.vertical", value: "library") { LibraryScreen() }
25            }
26            .tabViewStyle(.sidebarAdaptable)
27            // Red tab highlight while the Sky tab is in night mode.
28            .tint(router.tab == "sky" && nightActive ? SkyStyle.nightRed : nil)
29            .preferredColorScheme(.dark)
30            .environment(\.openURL, InAppBrowser.action)
31            .fullScreenCover(isPresented: .constant(!onboarded)) {
32                OnboardingScreen().preferredColorScheme(.dark)
33            }
34            .onChange(of: scenePhase) { if scenePhase == .active { Task { await LaunchPassNotifications.refresh() } } }
35        }
36    }
37}
38
39final class AppDelegate: NSObject, UIApplicationDelegate, UNUserNotificationCenterDelegate {
40    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]? = nil) -> Bool {
41        ImageLoader.configureURLCache()
42        UNUserNotificationCenter.current().delegate = self
43        application.registerForRemoteNotifications()
44        return true
45    }
46
47    func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
48        let token = deviceToken.map { String(format: "%02x", $0) }.joined()
49        log.info("APNs device token: \(token, privacy: .public)")
50        Task { @MainActor in AuroraAlerts.shared.receivedToken(token) }
51    }
52
53    /// A news digest opens News & launches on the News switch.
54    nonisolated func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse) async {
55        guard response.notification.request.content.userInfo["tab"] as? String == "news" else { return }
56        await MainActor.run {
57            Router.shared.tab = "launches"
58            Router.shared.showNews = true
59        }
60    }
61
62    /// Show alerts as banners while the app is open.
63    nonisolated func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification) async -> UNNotificationPresentationOptions {
64        [.banner, .sound]
65    }
66
67    func application(_ application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: Error) {
68        log.error("APNs registration failed: \(error.localizedDescription, privacy: .public)")
69    }
70}