我有一个带有播放视频的表格视图单元的表格视图。我希望能够缓存我的视频(例如像Kingfisher或Alamaofire之类的库可以处理图像),以便不必在用户上下滚动时连续重新下载它们。有没有可以允许我执行此操作的库或预制的快速文件?
我尝试使用此答案Is it possible to cache Videos? IOS - Swift中提供的代码,但没有用。经过一些修改后,我无法修复它。
这是我正在使用的当前代码:
public enum Result<T> {
case success(T)
case failure(NSError)
}
class CacheManager {
static let shared = CacheManager()
private let fileManager = FileManager.default
private lazy var mainDirectoryUrl: URL = {
let documentsUrl = self.fileManager.urls(for: .cachesDirectory, in: .userDomainMask).first!
return documentsUrl
}()
func getFileWith(stringUrl: String, completionHandler: @escaping (Result<URL>) -> Void ) {
let file = directoryFor(stringUrl: stringUrl)
//return file path if already exists in cache directory
guard !fileManager.fileExists(atPath: file.path) else {
completionHandler(Result.success(file))
return
}
DispatchQueue.global().async {
if let videoData = NSData(contentsOf: URL(string: stringUrl)!) {
videoData.write(to: file, atomically: true)
DispatchQueue.main.async {
completionHandler(Result.success(file))
}
} else {
DispatchQueue.main.async {
completionHandler(Result.failure(NSError(domain: "Can't download video", code: 1717, userInfo: ["description": "Can't download video"])));
}
}
}
}
private func directoryFor(stringUrl: String) -> URL {
let fileURL = URL(string: stringUrl)!.lastPathComponent
let file = self.mainDirectoryUrl.appendingPathComponent(fileURL)
return file
}
}
很明显,此功能不会产生缓存的视频。任何帮助将不胜感激。