I have a file with .m3u8 format that I can play and can also cache to later play it offline using the below code:
class DownloadManager: NSObject {
static let shared = DownloadManager()
func setupAssetDownload(url:URL) {
//
let configuration = URLSessionConfiguration.background(withIdentifier: "streamVideo")
let downloadSession = AVAssetDownloadURLSession(configuration: configuration,
assetDownloadDelegate: self,
delegateQueue: OperationQueue.main)
let asset = AVURLAsset(url: url)
let downloadTask = downloadSession.makeAssetDownloadTask(asset: asset,
assetTitle: "",
assetArtworkData: nil,
options: nil)
downloadTask?.resume()
}
}
extension DownloadManager: AVAssetDownloadDelegate {
func urlSession(_ session: URLSession, assetDownloadTask: AVAssetDownloadTask, didFinishDownloadingTo location: URL) {
UserDefaults.standard.set(location.relativePath, forKey: "assetPath")
}
}
And later play it like this:
guard let assetPath = UserDefaults.standard.value(forKey: "assetPath") as? String else {
// Present Error: No offline version of this asset available
return
}
let baseURL = URL(fileURLWithPath: NSHomeDirectory())
let assetURL = baseURL.appendingPathComponent(assetPath)
let asset = AVURLAsset(url: assetURL)
if let cache = asset.assetCache, cache.isPlayableOffline {
let avItem = AVPlayerItem(asset: asset)
player = AVPlayer(playerItem: avItem)
player?.play()
}
But how can I save this to local disk so that user can share/download it while playing? Any help would be appreciated.