Created
August 16, 2023 01:45
-
-
Save yosshi4486/fac0752ca5ebd228c65b05f75ca1fd59 to your computer and use it in GitHub Desktop.
OnCommitModifier
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/// データをコミットすべきタイミングで実行されるModifier | |
/// | |
/// コミットされるタイミングは下記の3つ: | |
/// 1. `UIApplication.willTerminateNotification`通知を受け取ったとき | |
/// 2. `onDissapear`が呼び出されたとき | |
/// 3. `scenePhase`が`.background`に切り替わったとき | |
/// | |
/// このModifierは上記の3つをまとめて汎用的に取り扱えるシンタックスシュガーとなっている. | |
struct OnCommitModifier: ViewModifier { | |
/// コミット時に実行するアクション. | |
var action: () -> Void | |
@Environment(\.scenePhase) var scenePhase | |
func body(content: Content) -> some View { | |
content | |
.onDisappear { | |
action() | |
} | |
.onReceive(NotificationCenter.default.publisher(for: UIApplication.willTerminateNotification)) { _ in | |
action() | |
} | |
.onChange(of: scenePhase) { newValue in | |
if newValue == .background { | |
action() | |
} | |
} | |
} | |
} | |
extension View { | |
/// upstreamの`View`に`OnCommitModifier`を適応するメソッド | |
/// | |
/// - Parameter action: コミット時に実行したいアクション | |
/// - Returns: 何らかの具体ビュー | |
func onCommit(_ action: @escaping () -> Void) -> some View { | |
self.modifier(OnCommitModifier(action: action)) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment