ios – When observing a notification that may be posted “on a thread other than the one used to registered the observer,” how to ensure thread-safe UI work?

I observe when one AVPlayer ends the game to present one UIAlert at the end time.

NotificationCenter.default.addObserver(
  self,
  selector: #selector(presentAlert),
  name: .AVPlayerItemDidPlayToEndTime,
  object: nil
)

I’ve had several user reports about the warning that happens where they are not intended, such as the middle of the video after playback and about other views. I’m not able to reproduce this myself, but my guess is that it’s a thread problem, as AVPlayerItemDidPlayToEndTime says “the system may send this message on a different thread than the one used to register the observer.”

So how can I make sure the warning is on the main thread? Should I send to the main queue from inside my presentAlert function, or add the above observer with addObserver(forName:object:queue:using:) instead passing in the main operation queue?

Leave a Comment