metatext/Caches/PlayerCache.swift

30 lines
610 B
Swift
Raw Permalink Normal View History

2020-10-15 07:44:01 +00:00
// Copyright © 2020 Metabolist. All rights reserved.
import AVKit
final class PlayerCache {
2021-02-06 06:54:26 +00:00
private let cache = NSCache<NSURL, AVPlayer>()
2020-10-15 07:44:01 +00:00
private var allURLsCached = Set<URL>()
2021-02-06 06:54:26 +00:00
private init() {
cache.countLimit = 4
}
2020-10-15 07:44:01 +00:00
}
extension PlayerCache {
static let shared = PlayerCache()
2021-02-06 06:54:26 +00:00
func player(url: URL) -> AVPlayer {
2020-10-15 07:44:01 +00:00
if let player = cache.object(forKey: url as NSURL) {
return player
}
2021-02-06 06:54:26 +00:00
let player = AVPlayer(url: url)
2020-10-15 07:44:01 +00:00
cache.setObject(player, forKey: url as NSURL)
allURLsCached.insert(url)
return player
}
}