我在stackoverflow中搜索了答案,但没有一个符合我的需求。我正在Swift Cocoa macOS上创建时间跟踪应用程序,比如Hubstaff时间跟踪应用。目前运行一个计时器,我想在x段时间后检测用户的不活动状态,并发送一个通知,说明他已经空闲了x段时间。我是iOS和macOS开发的新手。我能举一个如何做的例子吗?
这是我的代码:
import Cocoa
class ViewController: NSViewController {
@IBOutlet weak var label: NSTextField!
@IBOutlet weak var playImage: NSButton!
var timer : Timer!
var isTimerWorking : Bool = false
var startTime : Date!
override func viewDidLoad() {
super.viewDidLoad()
}
@IBAction func playPause(_ sender: NSButton) {
if isTimerWorking {
endTimer()
playImage.image = NSImage(named: NSImage.Name("play"))
sender.state = .off
} else {
startTimer()
playImage.image = NSImage(named: NSImage.Name("stop"))
sender.state = .off
}
}
func startTimer() {
startTime = Date()
timer = Timer.scheduledTimer(
timeInterval: 1.0,
target: self,
selector: #selector(self.timerCounter),
userInfo: nil,
repeats: true
)
isTimerWorking = true
}
func endTimer() {
if timer != nil {
timer.invalidate()
label.stringValue = "00:00:00"
}
isTimerWorking = false
}
@objc func timerCounter() {
let currentTime = Date().timeIntervalSince(startTime)
let hour = Int(fmod(currentTime/3600, 60))
let minute = Int(fmod(currentTime/60, 60))
let second = Int(fmod(currentTime, 60))
let hourValue = String(format:"%02d", hour)
let minuteValue = String(format:"%02d", minute)
let secondValue = String(format:"%02d", second)
label.stringValue = "(hourValue):(minuteValue):(secondValue)"
}
}
在我自己的时间跟踪应用程序中,我使用
var lastEvent:CFTimeInterval = 0
lastEvent = CGEventSource.secondsSinceLastEventType(CGEventSourceStateID.hidSystemState, eventType: CGEventType(rawValue: ~0)!)
print(lastEvent)
以获得用户空闲时间。