I’ve a category CustomContainer
which I want to avoid wasting to fileManager. The Downside is that struct comprises AVPlayer
& AVPlayerItem
and I can not determine tips on how to deal with these. The construction of the code is in such a manner that I can not hold these AV
gadgets out of the category. I’m able to cache them however can not seem to save them in fileManager.
class CustomContainer {
var url: String
var reset: Bool = false {
didSet {
if reset {
participant.pause()
participant.search(to: .zero)
}
}
}
var shouldPlayVideo: Bool {
didSet {
if playOn && playerItem.standing == .readyToPlay {
participant.play()
} else {
participant.pause()
}
}
}
let participant: AVPlayer
let playerItem: AVPlayerItem
init(participant: AVPlayer, merchandise: AVPlayerItem, url: String) {
self.participant = participant
self.playerItem = merchandise
self.url = url
}
}
Beneath is how I’m utilizing this CustomContainer
class
func setupVideo(url: String) {
guard let URL = URL(string: url) else {
return
}
let asset = AVURLAsset(url: URL)
let requestedKeys = ["playable"]
asset.loadValuesAsynchronously(forKeys: requestedKeys) { [weak self] in
guard let strongSelf = self else {
return
}
var error: NSError?
let standing = asset.statusOfValue(forKey: "playable", error: &error)
change standing {
case .loaded:
break
case .failed, .cancelled:
print("Didn't load asset efficiently")
return
default:
print("Unkown state of asset")
return
}
let participant = AVPlayer()
let merchandise = AVPlayerItem(asset: asset)
DispatchQueue.fundamental.async {
let customContainer = CustomContainer(participant: participant, merchandise: merchandise, url: url)
//Saving in cache
strongSelf.videoCache.setObject(customContainer, forKey: url as NSString)
customContainer.participant.replaceCurrentItem(with: customContainer.playerItem)
}
}
}
Utilizing the customContainer object that’s saved in cache later to play video
func playVideo(withLayer layer: AVPlayerLayer, url: String) {
if let videoContainer = self.videoCache.object(forKey: url as NSString) {
layer.participant = videoContainer.participant
videoContainer.shouldPlayVideo = true
}
}