10

I have updated my code to swift 4 in Xcode 9. Before that it was working fine. But now AVplayer is crashing at observers below is the code where it is crashing.

addObserver(self, forKeyPath: "player.currentItem.duration", options: [.new, .initial], context: &playerViewControllerKVOContext)

And the log is

Terminating app due to uncaught exception 'NSUnknownKeyException',reason: '[ addObserver: forKeyPath:@"player.currentItem.duration" options:5 context:0x10ff74ac8] was sent to an object that is not KVC-compliant for the "player" property.'

pkamb
  • 33,281
  • 23
  • 160
  • 191
Shuja Ud Din
  • 434
  • 5
  • 17

1 Answers1

22

Swift does not have the Key value observer of its own so for Swift 4 we have to add:

@objc dynamic

before the property whose value you need to observe. In your case it will be the AVPlayer instance. e.g.:

class MyPlayerCustomView: UIView {

@objc dynamic var myPlayer: AVPlayer?

}

Hope this solves your problem. It did solve mine!

pkamb
  • 33,281
  • 23
  • 160
  • 191
Junaid Mukhtar
  • 815
  • 9
  • 16
  • 1
    As an explanation, dynamic makes the property to be dispatched by the Objective-C runtime. That's why @objc is needed too. – javi_swift May 30 '19 at 10:53