首页 > 解决方案 > macOS 拷贝检测

问题描述

基本上,我试图检测用户何时将某些内容复制到剪贴板并执行操作。在这种情况下,我正在尝试播放声音;我已将声音文件导入 Xcode。但是,它由于 while 循环而崩溃,如果我删除了 while 循环,它仍然会崩溃,因为我最后重新启动了程序。我应该怎么做,因为我总是陷入循环并最终程序崩溃并且无法检测到 NSPasteboard 的 changeCount 的变化。声音文件也不起作用,我似乎无法弄清楚为什么。任何帮助都是极好的!!!!只用 Swift 编写。

编辑1:我知道它为什么会崩溃,我只是不知道有什么其他方法可以做到这一点。

import Cocoa
import AVFoundation

class ViewController: NSViewController {
let pasteboard = NSPasteboard.general

override func viewDidLoad() {
    super.viewDidLoad()

    let sound = URL(fileURLWithPath: Bundle.main.path(forResource: "sound", ofType: "mp3")!)

    var audioPlayer: AVAudioPlayer?

    //intializing audio player
    do
    {
        try audioPlayer = AVAudioPlayer(contentsOf: sound)

    }catch{
        print("fail")
    }


    let lastChangeCount=pasteboard.changeCount

    //keep looping until something is copied.
    while(pasteboard.changeCount==lastChangeCount){

    }

    //something is copied to clipboard so play audio
    audioPlayer?.play()

    //restart program
    self.viewDidLoad()

  }

标签: macosswift3xcode9.4

解决方案


使用循环进行轮询while是非常不好的习惯,你绝不能调用viewDidLoad,永远不要。

此版本使用Timer每秒触发一次的 a 并检查闭包中的粘贴板。

播放简单的声音AVFoundation是大材小用

class ViewController: NSViewController {


    var lastChangeCount = 0
    var timer : Timer?

    override func viewDidLoad() {
        super.viewDidLoad()
        let pasteboard = NSPasteboard.general

        lastChangeCount = pasteboard.changeCount
        timer = Timer.scheduledTimer(withTimeInterval: 1.0, repeats: true) { [unowned self] timer in
            if pasteboard.changeCount != self.lastChangeCount {
                NSSound(named: NSSound.Name("sound"))?.play()
                self.lastChangeCount = pasteboard.changeCount
            }
        }
    }
}

推荐阅读