macos - 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()
}
解决方案
使用循环进行轮询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
}
}
}
}
推荐阅读
- javascript - 在用户更改其内容后读取输入框的值,可能吗?
- android - NavigationDrawer 中奇怪的单出项目
- node.js - 使用节点 js 检查 mongodb 中的唯一电子邮件
- ssl - 由 nginx 代理的 gerrit 仅在“托管”在顶级目录上时才有效
- javascript - 为什么 chrome.runtime.lastError 不进入
- ruby-on-rails - 为什么弹窗不显示也不删除页面?
- javascript - 从组件内的路由器链接中的单击事件调用方法(Vue.js)
- c++ - 为什么将 const ptr 分配给 const 引用时不会出现编译错误?
- hibernate - Spring JPA java.lang.ClassCastException:java.lang.Integer 无法转换为 com.gpch.hotel.model.User
- configuration - 尝试在远程服务器上配置弹性搜索时出现“master_not_discovered_exception”