0

In the newest SwiftUI template project there is no AppDelegate (like in the oldern-days :^) so where do I put the code to work with UserDefaults?

Any pointers? Thanks!

David
  • 141
  • 2
  • 12
  • `UserDefaults.standard` available everywhere, so in any action modifier like `.onAppear`, `.onChanged`, etc. And moreover AppDelegate is still there [SwiftUI life-cycle iOS14 Where to put AppDelegate code?](https://stackoverflow.com/a/62538373/12299030) – Asperi Aug 02 '20 at 05:41

2 Answers2

0

Now why didn't I think to do this... (because I'm a newbie). And coming from a Java world... where the one Class <-> one File rule has some werid influence upon code structure thinking. Got give up the Java.

import SwiftUI
import UIKit

// no changes in your AppDelegate class
class AppDelegate: NSObject, UIApplicationDelegate {
    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey : Any]? = nil) -> Bool {
        print(">> your code here !!")
        return true
    }
}

@main
struct Testing_SwiftUI2App: App {

    // inject into SwiftUI life-cycle via adaptor !!!
    @UIApplicationDelegateAdaptor(AppDelegate.self) var appDelegate

    var body: some Scene {
        WindowGroup {
            ContentView()
        }
    }
}
David
  • 141
  • 2
  • 12
  • I did not realize one could override a method in an unrelated file... this Swift is not like Java! – David Sep 08 '20 at 23:02
0

Of course if you want to use "pure" swiftUI, you could put your code in the init() of @main...

Like:

@main
struct Testing_SwiftUI2App: App {

    init() {
    // your userdefaults code here...
    }

    var body: some Scene {
        WindowGroup {
            ContentView()
        }
    }
}
Gerard
  • 1,807
  • 4
  • 13
  • 20