Apr 15, 2024 iOS

SwiftUI app life cycle iOS14 where to put AppDelegate code?

In SwiftUI apps targeting iOS 14 and later, you typically won’t have an AppDelegate file by default because SwiftUI apps rely on the @main attribute applied to your app’s main entry point, usually a struct that conforms to the App protocol. However, if you need to handle specific lifecycle events or implement functionality that requires access to the UIApplicationDelegate methods, you can still do so by creating a custom AppDelegate file.

Here’s how you can create and use a custom AppDelegate in a SwiftUI app targeting iOS 14:

  1. Create a new Swift file named AppDelegate.swift in your project.
  2. Define a class conforming to UIApplicationDelegate in the AppDelegate.swift file. For example:
import UIKit

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
    // Implement any necessary UIApplicationDelegate methods here
}
  1. Make sure to remove the @main attribute from your SwiftUI App struct, as it will conflict with the @UIApplicationMain attribute on the AppDelegate class.
  2. If you need to access the UIApplicationDelegate methods in your SwiftUI views, you can do so using the UIApplication.shared.delegate reference. For example:
import SwiftUI

struct ContentView: View {
    var body: some View {
        Text("Hello, World!")
            .onAppear {
                // Accessing UIApplicationDelegate methods
                if let delegate = UIApplication.shared.delegate as? AppDelegate {
                    // Call delegate methods here
                }
            }
    }
}
  1. Implement any necessary functionality or handle lifecycle events within the AppDelegate class as needed.

Remember that while SwiftUI provides a more declarative and SwiftUI-centric way of building user interfaces, there may still be scenarios where you need to interact with UIKit or handle specific lifecycle events using UIApplicationDelegate. In such cases, using a custom AppDelegate is the appropriate approach.

  1. Updating Existing Apps:
    • To update an existing app to use the SwiftUI life cycle:
      • Set the deployment target to iOS 14 or later.
      • Remove @UIApplicationMain from your AppDelegate.
      • Add the @main struct conforming to App as shown above.

Remember to adjust the code according to your specific requirements. The AppDelegate will now handle Firebase configuration during app launch, and you can access it directly from your SwiftUI views12.

If you have any other specific tasks that were previously handled in AppDelegate, you can similarly adapt them to the new SwiftUI life cycle.