Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
27 commits
Select commit Hold shift + click to select a range
6bf94eb
Remove Main.storyboard and migrate to SwiftUI app lifecycle
bjorkert Apr 18, 2026
05992d9
Migrate info table from UITableView to SwiftUI List
bjorkert Apr 18, 2026
94e23c0
Migrate statistics and pie chart from UIKit to SwiftUI
bjorkert Apr 18, 2026
69566eb
Migrate BG display area from UIKit labels to SwiftUI
bjorkert Apr 18, 2026
63e8307
Migrate main layout to SwiftUI with UIKit charts embedded
bjorkert Apr 18, 2026
7ed09ca
Clean up migration artifacts and fix post-migration bugs
bjorkert Apr 18, 2026
d5ed19c
Replace view hierarchy walking with MainViewController.shared
bjorkert Apr 18, 2026
561375b
Fix MainViewController.shared references for stats and treatments
bjorkert Apr 19, 2026
69434c9
Fix info table font size to match storyboard
bjorkert Apr 19, 2026
122c49e
Fix Share Logs sheet rendering blank
bjorkert Apr 21, 2026
f54847b
Merge remote-tracking branch 'origin/dev' into remove-storyboard
bjorkert Apr 26, 2026
db546b8
Fix back navigation from Settings sub-pages
bjorkert Apr 28, 2026
1a6f75f
Harden post-storyboard migration
bjorkert Apr 29, 2026
b26943b
MoreMenuView: render tab-switch buttons in primary color
bjorkert Apr 29, 2026
10b1d19
Merge remote-tracking branch 'origin/dev' into remove-storyboard
bjorkert Apr 29, 2026
30339e4
Revert MainViewController singleton bootstrap
bjorkert Apr 29, 2026
89d53d7
MoreMenuView: make tab-switch rows full-row tappable
bjorkert May 3, 2026
908b5bb
Merge remote-tracking branch 'origin/dev' into remove-storyboard
bjorkert May 3, 2026
10c31c3
Align units-selection conflict resolution with integration branch
bjorkert May 3, 2026
2ea11e0
MoreMenuView: fix cross-row tap routing in Features section
bjorkert May 3, 2026
2c35ee3
MoreMenuView: keep Settings as a value-based NavigationLink
bjorkert May 3, 2026
d25c182
Fix navigation between alarms and menu
bjorkert May 4, 2026
892a60f
Drive Before-First-Unlock recovery from AppDelegate
bjorkert May 4, 2026
ad84c7b
Keep MainViewController alive regardless of tab layout
bjorkert Jun 1, 2026
52b0ccb
Merge remote-tracking branch 'origin/dev' into remove-storyboard
bjorkert Jun 1, 2026
951e98e
Fix issues found in post-migration review
bjorkert Jun 11, 2026
ddb0a45
Fix squished Home layout caused by phantom keyboard inset
bjorkert Jun 12, 2026
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
84 changes: 44 additions & 40 deletions LoopFollow.xcodeproj/project.pbxproj

Large diffs are not rendered by default.

43 changes: 25 additions & 18 deletions LoopFollow/Alarm/AlarmsContainerView.swift
Original file line number Diff line number Diff line change
Expand Up @@ -4,28 +4,35 @@
import SwiftUI

struct AlarmsContainerView: View {
var onBack: (() -> Void)?
private let embedsInNavigationStack: Bool

init(embedsInNavigationStack: Bool = true) {
self.embedsInNavigationStack = embedsInNavigationStack
}

var body: some View {
NavigationStack {
AlarmListView()
.toolbar {
if let onBack {
ToolbarItem(placement: .navigationBarLeading) {
Button(action: onBack) {
Image(systemName: "chevron.left")
}
}
}
ToolbarItem(placement: .navigationBarTrailing) {
NavigationLink {
AlarmSettingsView()
} label: {
Image(systemName: "gearshape")
}
}
Group {
if embedsInNavigationStack {
NavigationStack {
content
}
} else {
content
}
}
.preferredColorScheme(Storage.shared.appearanceMode.value.colorScheme)
}

private var content: some View {
AlarmListView()
.toolbar {
ToolbarItem(placement: .navigationBarTrailing) {
NavigationLink {
AlarmSettingsView()
} label: {
Image(systemName: "gearshape")
}
}
}
}
}
176 changes: 104 additions & 72 deletions LoopFollow/Application/AppDelegate.swift
Original file line number Diff line number Diff line change
@@ -1,14 +1,12 @@
// LoopFollow
// AppDelegate.swift

import CoreData
import AVFoundation
import EventKit
import UIKit
import UserNotifications

@main
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
let notificationCenter = UNUserNotificationCenter.current()

func application(_: UIApplication, didFinishLaunchingWithOptions _: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
Expand Down Expand Up @@ -65,14 +63,49 @@ class AppDelegate: UIResponder, UIApplicationDelegate {

// Detect Before-First-Unlock launch. If protected data is unavailable here,
// StorageValues were cached from encrypted UserDefaults and need a reload
// on the first foreground after the user unlocks.
// once the device is unlocked.
let bfu = !UIApplication.shared.isProtectedDataAvailable
Storage.shared.needsBFUReload = bfu
LogManager.shared.log(category: .general, message: "BFU check: isProtectedDataAvailable=\(!bfu), needsBFUReload=\(bfu)")

// Recovery is driven from AppDelegate (not MainViewController) because under
// the SwiftUI App lifecycle the home tab's UIHostingController is materialized
// lazily — on a BG-only launch (BGAppRefreshTask, BLE wake) MainViewController
// may not exist when the device is unlocked, and would miss willEnterForeground.
// protectedDataDidBecomeAvailable fires the moment file protection lifts and
// is the authoritative signal; willEnterForeground is a fallback.
let nc = NotificationCenter.default
nc.addObserver(self, selector: #selector(protectedDataDidBecomeAvailable), name: UIApplication.protectedDataDidBecomeAvailableNotification, object: nil)
nc.addObserver(self, selector: #selector(handleWillEnterForeground), name: UIApplication.willEnterForegroundNotification, object: nil)

// Race guard: protected data may have become available between the check
// above and the observer registration just now.
if Storage.shared.needsBFUReload, UIApplication.shared.isProtectedDataAvailable {
performBFUReloadIfNeeded()
}

return true
}

// MARK: - BFU recovery

@objc private func protectedDataDidBecomeAvailable() {
performBFUReloadIfNeeded()
}

@objc private func handleWillEnterForeground() {
performBFUReloadIfNeeded()
}

private func performBFUReloadIfNeeded() {
guard Storage.shared.needsBFUReload else { return }
Storage.shared.needsBFUReload = false
LogManager.shared.log(category: .general, message: "BFU reload triggered — reloading all StorageValues")
Storage.shared.reloadAll()
LogManager.shared.log(category: .general, message: "BFU reload complete: url='\(Storage.shared.url.value)'")
NotificationCenter.default.post(name: .bfuReloadCompleted, object: nil)
}

func applicationWillTerminate(_: UIApplication) {
#if !targetEnvironment(macCatalyst)
LiveActivityManager.shared.endOnTerminate()
Expand Down Expand Up @@ -127,85 +160,31 @@ class AppDelegate: UIResponder, UIApplicationDelegate {
completionHandler(.newData)
}

// MARK: - URL handling

// Note: with scene-based lifecycle (iOS 13+), URLs are delivered to
// SceneDelegate.scene(_:openURLContexts:) — not here. The scene delegate
// handles <urlScheme>://la-tap for Live Activity tap navigation.

// MARK: UISceneSession Lifecycle

func application(_: UIApplication, willFinishLaunchingWithOptions _: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
// set the "prevent screen lock" option when the app is started
// This method doesn't seem to be working anymore. Added to view controllers as solution offered on SO
UIApplication.shared.isIdleTimerDisabled = Storage.shared.screenlockSwitchState.value

return true
}

// MARK: - Scene configuration

// Under the scene-based lifecycle (which the SwiftUI App lifecycle uses),
// UIKit delivers Home Screen quick actions and opened URLs to the window
// scene delegate — application(_:performActionFor:) is never called.
// Injecting a delegate class here is the supported way to receive those
// events; SwiftUI still creates and manages the window itself.
func application(_: UIApplication, configurationForConnecting connectingSceneSession: UISceneSession, options _: UIScene.ConnectionOptions) -> UISceneConfiguration {
// Called when a new scene session is being created.
// Use this method to select a configuration to create the new scene with.
UISceneConfiguration(name: "Default Configuration", sessionRole: connectingSceneSession.role)
}

func application(_: UIApplication, didDiscardSceneSessions _: Set<UISceneSession>) {
// Called when the user discards a scene session.
// If any sessions were discarded while the application was not running, this will be called shortly after application:didFinishLaunchingWithOptions.
// Use this method to release any resources that were specific to the discarded scenes, as they will not return.
}

// MARK: - Core Data stack

lazy var persistentContainer: NSPersistentCloudKitContainer = {
/*
The persistent container for the application. This implementation
creates and returns a container, having loaded the store for the
application to it. This property is optional since there are legitimate
error conditions that could cause the creation of the store to fail.
*/
let container = NSPersistentCloudKitContainer(name: "LoopFollow")
container.loadPersistentStores(completionHandler: { _, error in
if let error = error as NSError? {
// Replace this implementation with code to handle the error appropriately.
// fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.

/*
Typical reasons for an error here include:
* The parent directory does not exist, cannot be created, or disallows writing.
* The persistent store is not accessible, due to permissions or data protection when the device is locked.
* The device is out of space.
* The store could not be migrated to the current model version.
Check the error message to determine what the actual problem was.
*/
fatalError("Unresolved error \(error), \(error.userInfo)")
}
})
return container
}()

// MARK: - Core Data Saving support

func saveContext() {
let context = persistentContainer.viewContext
if context.hasChanges {
do {
try context.save()
} catch {
// Replace this implementation with code to handle the error appropriately.
// fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
let nserror = error as NSError
fatalError("Unresolved error \(nserror), \(nserror.userInfo)")
}
let configuration = UISceneConfiguration(name: nil, sessionRole: connectingSceneSession.role)
if connectingSceneSession.role == .windowApplication {
configuration.delegateClass = AppSceneDelegate.self
}
return configuration
}

func userNotificationCenter(_: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) {
if response.actionIdentifier == "OPEN_APP_ACTION" {
if let window {
window.rootViewController?.dismiss(animated: true, completion: nil)
window.rootViewController?.present(MainViewController(), animated: true, completion: nil)
}
// Dismiss any presented modal/sheet so the user actually sees Home
UIApplication.shared.topMost?.dismiss(animated: true)
Observable.shared.selectedTabIndex.value = 0
}

if response.actionIdentifier == "snooze" {
Expand All @@ -226,6 +205,59 @@ class AppDelegate: UIResponder, UIApplicationDelegate {
}
}

extension Notification.Name {
/// Posted by AppDelegate after a Before-First-Unlock recovery completes
/// (Storage.reloadAll has run with the now-decrypted UserDefaults).
static let bfuReloadCompleted = Notification.Name("LoopFollow.bfuReloadCompleted")
}

/// Window scene delegate installed via configurationForConnecting. SwiftUI owns
/// the window; this class only handles the events UIKit routes to the scene
/// delegate instead of the application delegate.
final class AppSceneDelegate: NSObject, UIWindowSceneDelegate {
private let speechSynthesizer = AVSpeechSynthesizer()

/// A quick action used to cold-launch the app arrives in the connection
/// options; windowScene(_:performActionFor:) is not called for that launch.
func scene(_: UIScene, willConnectTo _: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) {
if let shortcutItem = connectionOptions.shortcutItem {
handleShortcutItem(shortcutItem)
}
}

/// Called when the user taps the "Speak BG" Home Screen quick action while
/// the app is already running.
func windowScene(_: UIWindowScene, performActionFor shortcutItem: UIApplicationShortcutItem, completionHandler: @escaping (Bool) -> Void) {
completionHandler(handleShortcutItem(shortcutItem))
}

@discardableResult
private func handleShortcutItem(_ shortcutItem: UIApplicationShortcutItem) -> Bool {
guard let bundleIdentifier = Bundle.main.bundleIdentifier,
shortcutItem.type == bundleIdentifier + ".toggleSpeakBG"
else {
return false
}
Storage.shared.speakBG.value.toggle()
let message = Storage.shared.speakBG.value ? "BG Speak is now on" : "BG Speak is now off"
speechSynthesizer.speak(AVSpeechUtterance(string: message))
return true
}

/// With a custom scene delegate installed, UIKit delivers opened URLs here
/// rather than through SwiftUI's onOpenURL, so the Live Activity tap
/// handling from LoopFollowApp is mirrored. Posting twice is harmless —
/// the navigation it triggers is idempotent.
func scene(_: UIScene, openURLContexts URLContexts: Set<UIOpenURLContext>) {
guard URLContexts.contains(where: { $0.url.scheme == AppGroupID.urlScheme && $0.url.host == "la-tap" }) else { return }
#if !targetEnvironment(macCatalyst)
DispatchQueue.main.async {
NotificationCenter.default.post(name: .liveActivityDidForeground, object: nil)
}
#endif
}
}

extension AppDelegate: UNUserNotificationCenterDelegate {
func userNotificationCenter(_: UNUserNotificationCenter,
willPresent notification: UNNotification,
Expand Down
Loading
Loading