Skip to content

Instantly share code, notes, and snippets.

@ferologics
Created April 5, 2024 08:06
Show Gist options
  • Select an option

  • Save ferologics/3ac8a231f19cd8d4a8f29d311122b7bb to your computer and use it in GitHub Desktop.

Select an option

Save ferologics/3ac8a231f19cd8d4a8f29d311122b7bb to your computer and use it in GitHub Desktop.

Revisions

  1. ferologics created this gist Apr 5, 2024.
    41 changes: 41 additions & 0 deletions UserFromForegroundKillApp.swift
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,41 @@
    //
    // 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")
    }
    }
    }