🔧 AppDelegateの役割
- アプリ起動時の初期設定
- バックグラウンド移行・復帰の検知
- プッシュ通知の処理
- 外部URLスキームの受け取り
🧱 AppDelegateの基本構造(iOS 13未満)
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
func application(_ application: UIApplication,
didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
// アプリ起動時の処理
print("アプリが起動しました")
return true
}
func applicationWillResignActive(_ application: UIApplication) {
// アプリが非アクティブになる前
}
func applicationDidEnterBackground(_ application: UIApplication) {
// バックグラウンドに入ったとき
}
func applicationWillEnterForeground(_ application: UIApplication) {
// フォアグラウンドに戻る直前
}
func applicationDidBecomeActive(_ application: UIApplication) {
// 再びアクティブになったとき
}
func applicationWillTerminate(_ application: UIApplication) {
// アプリ終了直前
}
}
🆕 iOS 13以降の構成
iOS 13以降は SceneDelegate.swift も追加され、1つのアプリに複数ウィンドウが存在する前提で処理が分かれました。
// AppDelegate.swift
func application(_ application: UIApplication,
didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
// 初期化処理(通知設定など)
return true
}
画面遷移などは主に SceneDelegate に記述します。
📲 通知の登録・受信の例
import UserNotifications
func registerPushNotification() {
UNUserNotificationCenter.current().requestAuthorization(options: [.alert, .badge, .sound]) { granted, error in
if granted {
DispatchQueue.main.async {
UIApplication.shared.registerForRemoteNotifications()
}
}
}
}
このような通知の許可処理は、AppDelegate に記述するのが一般的です。
📌 よく使うメソッド
didFinishLaunchingWithOptions:起動完了時applicationDidEnterBackground:バックグラウンド移行applicationWillTerminate:終了直前