3

我在 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)"
}
}
4

1 回答 1

12

在我自己的时间跟踪应用程序中,我正在使用

var lastEvent:CFTimeInterval = 0
lastEvent = CGEventSource.secondsSinceLastEventType(CGEventSourceStateID.hidSystemState, eventType: CGEventType(rawValue: ~0)!)

print(lastEvent)

获取用户空闲时间。

于 2018-11-30T17:27:51.187 回答