SwiftUI projects do not generate with an AppDelegate file, which is a necessary component to install and configure New Relic functionality with iOS/tvOS applications. To add an AppDelegate to your SwiftUI App, follow the steps detailed here. Before adding the AppDelegate, follow the outlined procedure to correctly install the New Relic agent.
Add a new file to your project named
AppDelegateThen in that file add a class named
AppDelegatethat inherits fromNSObjectand conforms to theUIApplicationDelegateprotocol.In the
AppDelegateclass you created, add theapplication:didFinishLaunchingWithOptionsfunction.As close to the start of
application:didFinishLaunchingWithOptionsas possible addNewRelic.start(withApplicationToken: "APP_TOKEN")replacingAPP_TOKENwith your application token.Importante
To ensure proper instrumentation, you must call the agent on the first line of
didFinishLaunchingWithOptions(), and run the agent on the main thread. Starting the call later, on a background thread, or asynchronously can cause unexpected or unstable behavior.import UIKitimport NewRelicclass AppDelegate: NSObject, UIApplicationDelegate {func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey : Any]? = nil) -> Bool {NewRelic.start(withApplicationToken: "APP_TOKEN")return true}}In the main app structure object add the following line:
@UIApplicationDelegateAdaptor(AppDelegate.self) var appDelegate.@mainstruct SwiftUI_ExampleApp: App {@UIApplicationDelegateAdaptor(AppDelegate.self) var appDelegate
That is all you need to do to add an AppDelegate.swift file to your SwiftUI application and start the New Relic iOS agent in the recommended way.