DownloadingFileAsset
AVAsset子类,旨在与外部缓存服务一起工作
DownloadingFileAsset
是AVAsset
的子类。它允许在下载的同时读取或播放媒体文件,与原始版本相比,在窄网环境下更加健壮。
动机
媒体文件变得越来越大,从互联网下载它们是正常的。为了提供更好的用户体验,应用程序不会等待下载完整的媒体文件,而是会在下载过程中尽快开始消费。但是
- 当使用
AVURLAsset(url: localDiskURL)
时,它只读取当时在本地磁盘上存在的数据,并且停止读取。 - 我可以用
AVURLAsset(url: remoteURL)
来代替,但这意味着用户将下载文件两次。
苹果提供了与AVURLAsset
一起工作的自定义资源下载机制,这将有助于这种情况。
DownloadingFileAsset
是实现其的编译版本。
用法
使用本地文件URL及其预期文件大小实例化DownloadingFileAsset
let asset = DownloadingFileAsset(localFileURL: downloadCacheURL,
expectedFileSize: expectedFileSize)
它应该可用...但目前还没有。任何资产读取过程都以仅本地可用数据结束。
我们需要一个 Progressive Reading 的解决方案
// FIXME this is a workaround
self.playerItem = AVPlayerItem(asset: asset) // both need a strong reference
self.player = AVPlayer(playerItem: playerItem!)
注意:对于完全下载的文件,请使用 AVAsset
或其他类。
错误通知
错误将通过 NotificationCenter 通知。要接收这些通知,你可以按照以下方式编写代码:
NotificationCenter.default.addObserver(self,
selector: #selector(downloadError),
name: .AssetFileLoaderDelegateFailedToOpenFile,
object: asset.resourceLoader.delegate)
NotificationCenter.default.addObserver(self,
selector: #selector(downloadError),
name: .AssetFileLoaderDelegateReadTimeout,
object: asset.resourceLoader.delegate)
// ...
@objc func downloadError(_ notification: Notification) {
if let error = notification.userInfo?[AssetFileLoaderDelegateErrorKey] as? Error {
// manage the error
}
}
示例
要运行示例项目,首先克隆仓库,然后从 Example 目录运行 pod install
。
要求
iPhone iOS 9.3+
安装
DownloadFileAsset 可通过 CocoaPods 获取。[要安装,只需在 Podfile 中添加以下行]
pod 'DownloadingFileAsset'
作者
HANAI tohru, [email protected]
许可证
DownloadFileAsset 在 MIT 许可证下可用。更多信息请参阅 LICENSE 文件。