0
2

More than 1 year has passed since last update.

【SwiftUI】SwiftUIでライフサイクルを定義したい。AppDelegateしたい。

Posted at

概要

  • SwiftUIでもUIKit時代のアプリのライフサイクルを決めておきたいなと思う
  • 当たり前のことだけどメモ

ソースコード

  1. やり方は簡単。まず、AppDelegate.swiftを作成。

  2. 以下のように、AppDelegateクラスを継承する(今回は通知の許可リクエストをアプリ起動時にやってほしいことを想定)。

    AppDelegate.swift
    
    import UIKit
    
    class AppDelegate: NSObject, UIApplicationDelegate {
        
        func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey : Any]? = nil) -> Bool {
            // 通知の許可リク
            let center = UNUserNotificationCenter.current()
            center.requestAuthorization(options: [.alert, .sound, .badge]) { granted, error in
                if granted {
                    print("通知が許可されたよ")
                } else {
                    print("通知が拒否されたよ")
                }
            }
            return true
        }
    }
    
  3. デフォルトで作られるAppの構造体に以下のように@UIApplicationDelegateAdaptor(AppDelegate.self) var appDelegateを定義する。

    SampleApp.swift
    
    import SwiftUI
    
    @main
    struct SampleApp: App {
        
    +   @UIApplicationDelegateAdaptor(AppDelegate.self) var appDelegate
        
        var body: some Scene {
            WindowGroup {
                ContentView()
                    .environmentObject(LocationManager())
            }
        }
    }
    
  4. 以上。無事アプリが開いた時に通知許可云々のダイアログが出た。

0
2
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
0
2