LoginSignup
14
10

More than 3 years have passed since last update.

【SwiftUI】SwiftUIでAppDelegateの処理を実装する方法

Last updated at Posted at 2020-12-20

SwiftUIでアプリを作成していた際に、起動時の処理を実装する必要が生まれAppDelegateを実装する必要が出てきたので、その手順を備忘録として書き留めておきます。

生成されるファイルについて

Xcode 12でプロジェクトを新規作成するとLifecycleという項目が追加されています。

これをUIKit App Delegateにすることで今まで通りAppDelegateなどが作成されます。
一方でSwiftUI Appを選択すると<プロジェクト名>App.swiftファイルが生成されます。
今回は、後者の<プロジェクト名>App.swiftファイルでのAppDelegateの実装方法について記述していきます。

SwiftUI Appで起動時の処理を実装する方法

@UIApplicationDelegateAdaptorを使用することで、既存のAppDelegateを利用することができるようになります。


import SwiftUI

@main
struct SwiftUIAppSample: App {
    // swiftlint:disable weak_delegate
    @UIApplicationDelegateAdaptor(AppDelegate.self) var appDelegate  // 追加する
    var body: some Scene {
        WindowGroup {
            ContentView()
        }
    }
}

// 以下を追加する
class AppDelegate: UIResponder, UIApplicationDelegate {
    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey : Any]? = nil) -> Bool {
        return true
    }
    // 必要に応じて処理を追加
}

UIKit App Delegateよりもコード記述量を減らして実装することができます。

以上がSwiftUIでAppDelegateを実装する手順になります。

14
10
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
14
10