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 an
AVPlayer finishes play in order to present a
UIAlert at the end time.
NotificationCenter.default.addObserver( self, selector: #selector(presentAlert), name: .AVPlayerItemDidPlayToEndTime, object: nil )
I’ve had multiple user reports of the alert happening where they’re not intended, such as the middle of the video after replaying, and on other views. I’m unable to reproduce this myself, but my guess is that it’s a threading issue since AVPlayerItemDidPlayToEndTime says “the system may post this notification on a thread other than the one used to registered the observer.”
How then do I make sure the alert is present on the main thread? Should I dispatch to the main queue from within my
presentAlert function, or add the above observer with
addObserver(forName:object:queue:using:) instead, passing in the main operation queue?