Skip to content

Commit cd746f3

Browse files
committed
Old cache directory keep in disk when new URLCache object assigned
1 parent b30d39a commit cd746f3

File tree

2 files changed

+47
-36
lines changed

2 files changed

+47
-36
lines changed

Foundation/URLCache.swift

+41-31
Original file line numberDiff line numberDiff line change
@@ -157,12 +157,14 @@ open class URLCache : NSObject {
157157
if let cache = sharedCache {
158158
return cache
159159
} else {
160+
guard var cacheDirectoryUrl = FileManager.default.urls(for: .cachesDirectory, in: .userDomainMask).first else {
161+
fatalError("Unable to find cache directory")
162+
}
163+
160164
let fourMegaByte = 4 * 1024 * 1024
161165
let twentyMegaByte = 20 * 1024 * 1024
162-
let bundleIdentifier = Bundle.main.bundleIdentifier ?? UUID().uuidString
163-
let cacheDirectoryPath = FileManager.default.urls(for: .cachesDirectory, in: .userDomainMask).first?.path ?? "\(NSHomeDirectory())/Library/Caches"
164-
let diskPath = cacheDirectoryPath + "/" + bundleIdentifier
165-
let cache = URLCache(memoryCapacity: fourMegaByte, diskCapacity: twentyMegaByte, diskPath: diskPath)
166+
cacheDirectoryUrl.appendPathComponent(ProcessInfo.processInfo.processName)
167+
let cache = URLCache(memoryCapacity: fourMegaByte, diskCapacity: twentyMegaByte, diskPath: cacheDirectoryUrl.path)
166168
sharedCache = cache
167169
cache.persistence?.setupCacheDirectory()
168170
return cache
@@ -173,8 +175,6 @@ open class URLCache : NSObject {
173175
guard newValue !== sharedCache else { return }
174176

175177
sharedSyncQ.sync {
176-
// Remove previous data before resetting new URLCache instance
177-
URLCache.sharedCache?.persistence?.deleteAllCaches()
178178
sharedCache = newValue
179179
newValue.persistence?.setupCacheDirectory()
180180
}
@@ -201,7 +201,7 @@ open class URLCache : NSObject {
201201
self.memoryCapacity = memoryCapacity
202202
self.diskCapacity = diskCapacity
203203

204-
if let _path = path {
204+
if diskCapacity > 0, let _path = path {
205205
self.persistence = _CachePersistence(path: _path)
206206
}
207207

@@ -290,7 +290,7 @@ open class URLCache : NSObject {
290290
@result the current usage of the on-disk cache of the receiver.
291291
*/
292292
open var currentDiskUsage: Int {
293-
return self.syncQ.sync { self.persistence?.cacheSizeInDesk ?? 0 }
293+
return self.syncQ.sync { self.persistence?.cacheSizeInDisk ?? 0 }
294294
}
295295

296296
}
@@ -305,7 +305,9 @@ fileprivate struct _CachePersistence {
305305

306306
let path: String
307307

308-
var cacheSizeInDesk: Int {
308+
// FIXME: Create a stored property
309+
// Update this value as the cache added and evicted
310+
var cacheSizeInDisk: Int {
309311
do {
310312
let subFiles = try FileManager.default.subpathsOfDirectory(atPath: path)
311313
var total: Int = 0
@@ -321,10 +323,6 @@ fileprivate struct _CachePersistence {
321323

322324
func setupCacheDirectory() {
323325
do {
324-
if FileManager.default.fileExists(atPath: path) {
325-
try FileManager.default.removeItem(atPath: path)
326-
}
327-
328326
try FileManager.default.createDirectory(atPath: path, withIntermediateDirectories: true)
329327
} catch {
330328
fatalError("Unable to create directories for URLCache: \(error.localizedDescription)")
@@ -334,15 +332,21 @@ fileprivate struct _CachePersistence {
334332
func saveCachedResponse(_ response: CachedURLResponse, for request: URLRequest) {
335333
let archivedData = NSKeyedArchiver.archivedData(withRootObject: response)
336334
do {
337-
let cacheFileURL = urlForFileIdentifier(request.cacheFileIdentifier)
338-
try archivedData.write(to: cacheFileURL)
335+
if let fileIdentifier = request.cacheFileIdentifier {
336+
let cacheFileURL = urlForFileIdentifier(fileIdentifier)
337+
try archivedData.write(to: cacheFileURL)
338+
}
339339
} catch {
340340
fatalError("Unable to save cache data: \(error.localizedDescription)")
341341
}
342342
}
343343

344344
func cachedResponse(for request: URLRequest) -> CachedURLResponse? {
345-
let url = urlForFileIdentifier(request.cacheFileIdentifier)
345+
guard let fileIdentifier = request.cacheFileIdentifier else {
346+
return nil
347+
}
348+
349+
let url = urlForFileIdentifier(fileIdentifier)
346350
guard let data = try? Data(contentsOf: url),
347351
let response = NSKeyedUnarchiver.unarchiveObject(with: data) as? CachedURLResponse else {
348352
return nil
@@ -351,29 +355,35 @@ fileprivate struct _CachePersistence {
351355
return response
352356
}
353357

354-
func deleteAllCaches() {
355-
do {
356-
try FileManager.default.removeItem(atPath: path)
357-
} catch {
358-
fatalError("Unable to flush database for URLCache: \(error.localizedDescription)")
359-
}
360-
}
361-
362358
private func urlForFileIdentifier(_ identifier: String) -> URL {
363-
return URL(fileURLWithPath: path + "/" + identifier)
359+
return URL(fileURLWithPath: path).appendingPathComponent(identifier)
364360
}
365361

366362
}
367363

368-
fileprivate extension URLRequest {
364+
extension URLRequest {
365+
366+
fileprivate var cacheFileIdentifier: String? {
367+
guard let scheme = self.url?.scheme, scheme == "http" || scheme == "https",
368+
let method = httpMethod, !method.isEmpty,
369+
let urlString = url?.absoluteString else {
370+
return nil
371+
}
372+
373+
var hashString = "\(scheme)_\(method)_\(urlString)"
374+
if let userAgent = self.allHTTPHeaderFields?["User-Agent"], !userAgent.isEmpty {
375+
hashString.append(contentsOf: "_\(userAgent)")
376+
}
377+
378+
if let acceptLanguage = self.allHTTPHeaderFields?["Accept-Language"], !acceptLanguage.isEmpty {
379+
hashString.append(contentsOf: "_\(acceptLanguage)")
380+
}
369381

370-
var cacheFileIdentifier: String {
371-
guard let urlString = url?.absoluteString else {
372-
fatalError("Unable to create cache identifier for request: \(self)")
382+
if let range = self.allHTTPHeaderFields?["Range"], !range.isEmpty {
383+
hashString.append(contentsOf: "_\(range)")
373384
}
374385

375-
let method = httpMethod ?? "GET"
376-
return urlString + method
386+
return String(format: "%X", hashString.hashValue)
377387
}
378388

379389
}

TestFoundation/TestURLCache.swift

+6-5
Original file line numberDiff line numberDiff line change
@@ -16,11 +16,12 @@ class TestURLCache: XCTestCase {
1616
}
1717

1818
private var cacheDirectoryPath: String {
19-
if let path = FileManager.default.urls(for: .cachesDirectory, in: .userDomainMask).first?.path {
20-
return "\(path)/org.swift.TestFoundation"
21-
} else {
22-
return "\(NSHomeDirectory())/Library/Caches/org.swift.TestFoundation"
19+
guard var cacheDirectoryUrl = FileManager.default.urls(for: .cachesDirectory, in: .userDomainMask).first else {
20+
fatalError("Unable to find cache directory")
2321
}
22+
23+
cacheDirectoryUrl.appendPathComponent(ProcessInfo.processInfo.processName)
24+
return cacheDirectoryUrl.path
2425
}
2526

2627
func test_cacheFileAndDirectorySetup() {
@@ -35,7 +36,7 @@ class TestURLCache: XCTestCase {
3536
let newPath = cacheDirectoryPath + ".test_cacheFileAndDirectorySetup/"
3637
URLCache.shared = URLCache(memoryCapacity: fourMegaByte, diskCapacity: twentyMegaByte, diskPath: newPath)
3738
XCTAssertTrue(FileManager.default.fileExists(atPath: newPath))
38-
XCTAssertFalse(FileManager.default.fileExists(atPath: cacheDirectoryPath))
39+
XCTAssertTrue(FileManager.default.fileExists(atPath: cacheDirectoryPath))
3940
}
4041

4142
}

0 commit comments

Comments
 (0)