是否可以缓存视频? iOS-迅捷 [英] Is it possible to cache Videos? IOS - Swift
问题描述
我正尝试在tableView之类的Instagram,vine或什至facebook中下载和播放视频。
I am trying to download and play videos in a tableView like Instagram, vine or even facebook.
我想要实现的是一个tableView,其中显示了视频,它们会在滚动时自动下载并播放。像Instagram ...
What I am trying to achieve is a tableView where I display the videos and they auto download and play while scrolling. Like Instagram...
到目前为止,我已经完成了大部分工作,但是我想改变的是,每次查看单元格时都会下载视频一次又一次....当然,必须有一种缓存视频的方法,或者只下载一次相同的视频....就像您对SDWebImages进行图像处理一样。
So far I have managed most of that, but what I would like to change is the fact that every time I view a cell the video gets downloaded again and again.... Surely there must be a way to cache videos, or only download the same video once.... Like you do with SDWebImages for images.
每当我查看单元格时,此刻也下载该文件,滚动就像您可以想象的那样可怕。
Also at the moment with it download every time I view the cell, the scrolling is terrible as you can imagine.
现在我似乎无法弄清楚Instagram是如何做到的。 ,但我100%确保他们不会一次下载同一视频!
Now I cannot seem to figure out how Instagram does it, but I am 100% sure they don't download the same video more than once!!
如果有人有建议和想法,我很想听听他们的意见!!
If anyone has and advice or ideas, I'd love to hear them!!
非常感谢。
推荐答案
使用Haneke,我无法检索缓存视频的文件路径。我通过将视频保存在缓存的目录中来处理它。
Using Haneke, I wasn't able to retrieve file path for cached video. I handled it by saving video in cached directory.
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.errorWith(text: "Can't download video")))
}
}
}
}
private func directoryFor(stringUrl: String) -> URL {
let fileURL = URL(string: stringUrl)!.lastPathComponent
let file = self.mainDirectoryUrl.appendingPathComponent(fileURL)
return file
}
}
此类的示例用法如下:
CacheManager.shared.getFileWith(stringUrl: "http://techslides.com/demos/sample-videos/small.mp4") { result in
switch result {
case .success(let url):
// do some magic with path to saved video
case .failure(let error):
// handle errror
}
}
这篇关于是否可以缓存视频? iOS-迅捷的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!