Raffi
Raffi

Reputation: 757

Why is AVPlayerItem not firing its notifications?

I have tried all AVPlayerItem notification with no luck.... Nothing is happening when the notification should post.

I'm trying to download a video from a website in WKWebView

Here is my code it is in swift 3.0

override func viewDidLoad() {
    super.viewDidLoad()

    NotificationCenter.default().addObserver(self, selector: #selector(self.downloadAudioVisualItem), name: NSNotification.Name.AVPlayerItemNewAccessLogEntry, object: nil)
}

func downloadAudioVisualItem() {
    print("Hello")
}

override func viewDidDisappear(_ animated: Bool) {
    super.viewDidDisappear(false)

    NotificationCenter.default().removeObserver(self)
}

Upvotes: 6

Views: 1628

Answers (1)

user6375148
user6375148

Reputation:

It appears that you are calling postNotification before even adding the observer. I mean the observer should be called first, so that only It can start listening for the notification.

Try this in App Delegate

import AVFoundation

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {

        let MyGreatNotification = Notification.Name.AVPlayerItemNewAccessLogEntry
        NotificationCenter.default().addObserver(self, selector: #selector(self.hello), name: MyGreatNotification, object: nil)
        return true
    }

    func hello()
    {
      // Put break point here
    }

And add posting notification code in your initial view controller like this.

import AVFoundation

override func viewDidLoad() {
        super.viewDidLoad()

        let MyGreatNotification = Notification.Name.AVPlayerItemNewAccessLogEntry
        NotificationCenter.default().post(name: MyGreatNotification, object: self)
    }

That's it try running your app, you can see that the app will break at the function named hello in App Delegate.

If you are still not sure. Do this, put this posting notification code in App Delegate and put adding observer code in initial view controller, add the selector and put a break point in there, try running the app. You can see that the app didn't break at the break point in the initial view controller.

Upvotes: -1

Related Questions