TLDR:根据我当前的 cacheManager,我如何清除缓存?我应该使用什么代码以及如何使用?
我有用于缓存用户创建的视频的波纹管 cacheManager 类。关于我如何使用它的更多信息在这里。
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 {
let error = NSError(domain: "SomeErrorDomain", code: -2001 /* some error code */, userInfo: ["description": "Can't download video"])
completionHandler(Result.failure(error))
}
}
}
}
private func directoryFor(stringUrl: String) -> URL {
let fileURL = URL(string: stringUrl)!.lastPathComponent
let file = self.mainDirectoryUrl.appendingPathComponent(fileURL)
return file
}
public func clearCache() {
//Delete Cookies
if let cookies = HTTPCookieStorage.shared.cookies {
for cookie in cookies {
NSLog("\(cookie)")
}
}
let storage = HTTPCookieStorage.shared
for cookie in storage.cookies! {
storage.deleteCookie(cookie)
}
}
}
我最近遇到了一个我在这里问过的问题。
为了解决这个问题,我相信我需要清除缓存。问题是我不知道该怎么做。
我尝试了什么:
public func clearCache() {
//Delete Cookies
if let cookies = HTTPCookieStorage.shared.cookies {
for cookie in cookies {
NSLog("\(cookie)")
}
}
let storage = HTTPCookieStorage.shared
for cookie in storage.cookies! {
storage.deleteCookie(cookie)
}
}
一旦出现第一个获取内容的实例,就会像这样使用。
CacheManager.clearCache()//Instance member 'clearCache' cannot be used on type 'CacheManager'; did you mean to use a value of this type instead?
self.getFollowers()
关于我如何使用缓存管理器的一些信息:
- 对于获取的每个媒体,我使用缓存管理器来存储视频 url(我假设是缓存的 videoURL)以供需要时使用