This is how in my code, playing from url, looks like:
private func play() {
let streamUrl = ...
let playerItem = AVPlayerItem(url: streamURL)
radioPlayer = AVPlayer(playerItem: playerItem)
radioPlayer.volume = 1.0
do {
try AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryPlayback, with: AVAudioSessionCategoryOptions.mixWithOthers)
try AVAudioSession.sharedInstance().setActive(true)
UIApplication.shared.beginReceivingRemoteControlEvents()
} catch {
print("Error deactivating audio session.")
}
radioPlayer.play()
startListeningForStreamFail()
stopStartButton.setImage(#imageLiteral(resourceName: "pause_btn"), for: .normal)
}
Like the code snippet explains above, after calling the .play()
function, I'm calling startListeningForStreamFail()
, which registers the current viewcontroller to two types of notifications, on main thread.
private func startListeningForStreamFail() {
DispatchQueue.main.async { [weak self] in
NotificationCenter.default.addObserver(self as Any, selector: #selector(self?.playerItemFailedToPlay), name: NSNotification.Name.AVPlayerItemPlaybackStalled, object: self?.radioPlayer?.currentItem)
NotificationCenter.default.addObserver(self as Any, selector: #selector(self?.playerItemFailedToPlay), name: NSNotification.Name.AVPlayerItemFailedToPlayToEndTime, object: self?.radioPlayer?.currentItem)
}
}
And the selector functions is this:
@objc private func playerItemFailedToPlay(notification: Notification) {
print("playerItemFailedToPlay")
}
Because the stream right now works fine, I'm trying to test failure by addig some plus characters in it's url. But the playerItemFailedToPlay()
functions does NOT get called, does NOT print anything.
Should this selector getting called, even if only the url was changed?
Any help would be appreciated. Thanks!