Skip to content

Instantly share code, notes, and snippets.

@ferologics
Created April 5, 2024 08:06
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ferologics/3ac8a231f19cd8d4a8f29d311122b7bb to your computer and use it in GitHub Desktop.
Save ferologics/3ac8a231f19cd8d4a8f29d311122b7bb to your computer and use it in GitHub Desktop.
Detect user killing the app from foreground
//
// 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