You should set an observer for the remote AVPlayerItem's status change.
self.statusObservation = nil // remove observer for outdated items
self.statusObservation = self.avPlayer?.currentItem?.observe(\AVPlayerItem.status) { [weak self] item, _ in
guard let self = self else { return }
// prevent reading duration from an outdated item:
guard item == self.avPlayer?.currentItem else { return }
if item.status == .readyToPlay {
item.duration.seconds // the duration you need.
}
}
Basically, when a remote AVPlayerItem has just being set, the AVPlayer knows nothing about the resource at all. It needs some time to retrieve the meta info, which includes the total duration.