3

I'm implementing a Quick Look Preview extension on macOS that will preview some unsupported audio types.

To be able to stop the audio playback when the user stops previewing, I'm pausing my audio engine in -viewDidDisappear.

However, the problem is that -viewDidDisappear is only called when exiting out of Quick Look in Finder altogether, not when I'm navigating to the next/previous file with the arrow keys.

class PreviewViewController: NSViewController, QLPreviewingController {
    func preparePreviewOfFile(at url: URL, completionHandler handler: @escaping (Error?) -> Void) {
        player.load(url)
        player.play()
    }
    
    override func viewDidDisappear() {
        // Not called when switching to the next or previous preview in Finder!
        player.stop()
    }
}

I've tried going through all the usual suspects on both NSViewController (-removeFromParent, -viewWillDisappear, -viewDidDisappear) and it's NSView (-viewDidHide, -viewDidMoveToWindow, -viewDidMoveToSuperview), but without success.

Neither of them are called when I switch to a different file in the Quick Look preview in Finder with the arrow keys (resulting in the audio just continuing to play while I'm Quick Looking some other file).

Anyone knows how to know if my preview view controller has been hidden?

adeasismont
  • 245
  • 1
  • 8

1 Answers1

0

I had the same issue and could not find any public APIs to get notified.

I came up with the following code that works on Ventura.

override func viewDidLoad() {
    super.viewDidLoad()
    
    timer = Timer.scheduledTimer(withTimeInterval: 0.1, repeats: true, block: { [weak self] _ in
        self?.timerHandler()
    })
}

@objc func timerHandler() {
    // Hack to find out if we are the top presented window
    if let window = view.window {
        let isActive = window.level.rawValue > 0
        if active {
            player.resume()
        } else {
            player.stop()
        }
    }
}

This might not make it through an App Store review, but you can always obfuscate it a little bit. I've seen many companies ship similar fixes over the years. As long as it's harmless it should be ok.

rumori
  • 11
  • 2