Created
April 5, 2024 08:06
-
-
Save ferologics/3ac8a231f19cd8d4a8f29d311122b7bb to your computer and use it in GitHub Desktop.
Detect user killing the app from foreground
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
// | |
// UserFromForegroundKillApp.swift | |
// UserFromForegroundKill | |
// | |
// Created by f h on 12/03/2024. | |
// | |
import SwiftUI | |
@main | |
struct UserFromForegroundKillApp: App { | |
@UIApplicationDelegateAdaptor private var appDelegate: MyAppDelegate | |
var body: some Scene { | |
WindowGroup { | |
ContentView() | |
} | |
} | |
} | |
final class MyAppDelegate: NSObject, UIApplicationDelegate { | |
var lastEnteredBackgroundDate: Date? = nil | |
let nc = NotificationCenter.default | |
var subs = [NSObjectProtocol]() | |
override init() { | |
super.init() | |
subs.append(nc.addObserver(forName: UIApplication.willResignActiveNotification, object: nil, queue: nil) { notification in | |
self.lastEnteredBackgroundDate = .now | |
print("willResignActiveNotification") | |
}) | |
} | |
func applicationWillTerminate(_ application: UIApplication) { | |
print("terminated") | |
if let lastEnteredBackgroundDate, Date.now.timeIntervalSince1970 - lastEnteredBackgroundDate.timeIntervalSince1970 < 2 { | |
print("by user") | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment