Basically, I'm trying to detect when the user has copied something to the clipboard and perform an action. In this case, I am trying to play a sound; I have imported the sound file to Xcode. However, It crashes because of the while loop and if I remove the while loop it still crashes because I restart the program in the end. How should I go about doing this because I always end up in a loop and eventually program crashes and can't detect a change in the NSPasteboard's changeCount. Also the sound file does not work, and I can't seem to figure out why. Any help would be awesome!!!! Writing it in Swift only.
Edit 1: I know why it's crashing, I just don't know any other way to do it.
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()
}