print the app in focus every 20 seconds in swift

You can use NSWorkspace to get the focused application and Timer to schedule the printing of the app's name every 20 seconds. Here's an example implementation:

main.swift
import Cocoa

class ViewController: NSViewController {
    
    var timer: Timer?
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        // Schedule the timer to print the focused app's name every 20 seconds
        timer = Timer.scheduledTimer(withTimeInterval: 20.0, repeats: true) { [weak self] _ in
            guard let self = self else { return }
            if let focusedApp = NSWorkspace.shared.frontmostApplication {
                print("Focused App: \(focusedApp.localizedName ?? "")")
            }
        }
    }
    
    deinit {
        // Invalidate the timer when the view controller is deallocated
        timer?.invalidate()
    }
    
}
689 chars
25 lines

In this implementation, we create a timer that fires every 20 seconds using scheduledTimer(withTimeInterval:repeats:block:). The block prints the name of the frontmost application by accessing NSWorkspace.shared.frontmostApplication. The timer is retained by the view controller and invalidated when the view controller is deallocated, to prevent any retain cycles.

gistlibby LogSnag