AppUsageManager.swift 1.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940
  1. import AppKit
  2. import Combine
  3. import Foundation
  4. @MainActor
  5. final class AppUsageManager {
  6. static let shared = AppUsageManager()
  7. static let didCompleteFirstSession = Notification.Name("AppUsageManager.didCompleteFirstSession")
  8. private static let hasCompletedFirstSessionKey = "AppUsageManager.hasCompletedFirstSession"
  9. private let defaults: UserDefaults
  10. private var cancellables = Set<AnyCancellable>()
  11. private init(defaults: UserDefaults = .standard) {
  12. self.defaults = defaults
  13. }
  14. /// `true` until the user has finished their first app session.
  15. var isFirstTimeUser: Bool {
  16. !defaults.bool(forKey: Self.hasCompletedFirstSessionKey)
  17. }
  18. func start() {
  19. guard cancellables.isEmpty else { return }
  20. NotificationCenter.default.publisher(for: NSApplication.willResignActiveNotification)
  21. .sink { [weak self] _ in
  22. self?.markFirstSessionCompleted()
  23. }
  24. .store(in: &cancellables)
  25. }
  26. func markFirstSessionCompleted() {
  27. guard isFirstTimeUser else { return }
  28. defaults.set(true, forKey: Self.hasCompletedFirstSessionKey)
  29. NotificationCenter.default.post(name: Self.didCompleteFirstSession, object: nil)
  30. }
  31. }