Skip to content

Instantly share code, notes, and snippets.

@voxels
Last active January 6, 2020 14:15
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save voxels/ab46ffc3c50fdd4a9675f4e05ae68a1c to your computer and use it in GitHub Desktop.
Save voxels/ab46ffc3c50fdd4a9675f4e05ae68a1c to your computer and use it in GitHub Desktop.
A URLCache handler for overriding the default shared cache settings
//
// CacheHandler.swift
// ToyPhotoGallery
//
// Created by Michael Edgcumbe on 7/14/18.
// Copyright © 2018 Michael Edgcumbe. All rights reserved.
//
import Foundation
class CacheHandler : LaunchService {
static let sharedCache:URLCache = URLCache()
var launchControlKey: LaunchControlKey?
/// The default number of megabytes for the memory cache
let defaultMemoryCacheSize:Int = 16
/// The default number of megabytes for the disk cache
let defaultDiskCacheSize:Int = 32
func launch(with key: String?, with center: NotificationCenter) throws {
let cache = URLCache(memoryCapacity: bytes(in: defaultMemoryCacheSize), diskCapacity: bytes(in: defaultDiskCacheSize), diskPath: getDocumentsDirectory().absoluteString)
URLCache.shared = cache
center.post(name: Notification.Name.DidLaunchSharedCached, object: nil)
}
func storeResponse(request:URLRequest, response:URLResponse?, data:Data?, completion:((Data?)->Void)?) {
guard let response = response, let data = data else {
completion?(nil)
return
}
let cachedResponse = CachedURLResponse(response: response, data: data)
URLCache.shared.storeCachedResponse(cachedResponse, for: request)
}
func cachedData(for request:URLRequest)->Data? {
if let cachedResponse = URLCache.shared.cachedResponse(for: request) {
return cachedResponse.data
}
return nil
}
}
extension CacheHandler {
func bytes(in megabytes:Int)->Int {
return megabytes * 1024 * 1024
}
// https://www.hackingwithswift.com/example-code/system/how-to-find-the-users-documents-directory
func getDocumentsDirectory() -> URL {
let paths = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)
let documentsDirectory = paths[0]
return documentsDirectory
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment