| 12345678910111213141516171819202122232425262728293031323334353637383940 |
- import AppKit
- import Combine
- import Foundation
- @MainActor
- final class AppUsageManager {
- static let shared = AppUsageManager()
- static let didCompleteFirstSession = Notification.Name("AppUsageManager.didCompleteFirstSession")
- private static let hasCompletedFirstSessionKey = "AppUsageManager.hasCompletedFirstSession"
- private let defaults: UserDefaults
- private var cancellables = Set<AnyCancellable>()
- private init(defaults: UserDefaults = .standard) {
- self.defaults = defaults
- }
- /// `true` until the user has finished their first app session.
- var isFirstTimeUser: Bool {
- !defaults.bool(forKey: Self.hasCompletedFirstSessionKey)
- }
- func start() {
- guard cancellables.isEmpty else { return }
- NotificationCenter.default.publisher(for: NSApplication.willResignActiveNotification)
- .sink { [weak self] _ in
- self?.markFirstSessionCompleted()
- }
- .store(in: &cancellables)
- }
- func markFirstSessionCompleted() {
- guard isFirstTimeUser else { return }
- defaults.set(true, forKey: Self.hasCompletedFirstSessionKey)
- NotificationCenter.default.post(name: Self.didCompleteFirstSession, object: nil)
- }
- }
|