WastedTime Watch – Progress

Ok, I had basically gotten frustrated trying to change WastedTime Watch to a fully SwiftUI based app. Apple changed the App Entry point which had completely changed how the AppDelegate function worked. I thought this app was the simplest of my apps, so I could easily convert it to the new Swift Architecture. Boy was I mistaken.

In September, after banging my head against the wall for days, I posted the problem on StackOverflow, and walked away. Over the last few months, I got a coupled of suggestions, but severally figured out how to address the problems.

The net of the problem was I could not create my start up objects multiple times, but always ended up with a nil object. The basic startup of the application had changed, and I was not following it.

Today while trying another suggestion, I finally realized that the problem was (here comes the big surprising reveal) – Me! I had been using a local object instead of the delegate I created. here’s the basic structure of the now working code!

//
//  WastedTimeWatchApp.swift
//  TestMe WatchKit Extension
//
//  Created by Michael Rowe on 9/22/20.
//  Copyright © 2020 Michael Rowe. All rights reserved.
//

import SwiftUI

struct DelegateKey: EnvironmentKey {
    typealias Value = ExtensionDelegate
    static let defaultValue: ExtensionDelegate = ExtensionDelegate()
}

extension EnvironmentValues {
    var extensionDelegate: DelegateKey.Value {
        get {
            return self[DelegateKey.self]
        }
        set {
            self[DelegateKey.self] = newValue
        }
    }
}

@main
struct WastedTimeWatchApp: App {
    
    @WKExtensionDelegateAdaptor(ExtensionDelegate.self) var delegate
    
    let prefs:UserDefaults = UserDefaults(suiteName: suiteName)!
    
    @SceneBuilder var body: some Scene {
        WindowGroup {
            NavigationView {
                ContentView()
                    .environment(\.extensionDelegate, delegate)
            }
        }
        WKNotificationScene(controller: NotificationController.self, category: "myCategory")
    }
}

class ExtensionDelegate: NSObject, WKExtensionDelegate, ObservableObject {
    
    @Environment(\.extensionDelegate) static var shared

    var meetingSetup: MeetingSetup!
    var meetingStatistics:  MeetingStatistics!
    var meeting: Meeting!
    
    func applicationDidFinishLaunching() {
        // Perform any final initialization of your application.
        print("applicationDidFinishLaunching for watchOS")
        ExtensionDelegate.shared.meetingSetup = MeetingSetup()
        ExtensionDelegate.shared.meetingStatistics = MeetingStatistics()
        ExtensionDelegate.shared.meeting = Meeting()
    }
}

The secrete ended up being that I had been using self.meeting = Meeting() in applicationDidFinishLaunch which was never actually exposed to the rest of the program. Now I should able to clean up a few simple problems in the views, and release version 2.0 of Wasted Time for the Watch