Overview
VideoCacheManager is a singleton class that provides a two-tier caching system for video data. It uses both in-memory caching (NSCache) and disk-based caching (FileManager) to optimize video loading performance. All disk cache keys are encrypted using SHA-2 hashing for security.
Singleton Instance
Access the shared instance:Properties
In-memory cache for quick data retrieval. Named “VideoCache”.
File manager instance for disk-based caching operations.
URL pointing to the disk cache directory located at Documents/VideoCache.
Serial dispatch queue with label “com.VideoCache” for thread-safe operations.
Methods
storeDataToCache
Stores video data to both memory and disk cache asynchronously.The video data to cache.
Cache key, typically the absolute URL string of the video.
Optional file extension (e.g., “mp4”) to append to the cached file.
queryDataFromCache
Queries video data from cache with a three-tier fallback system:- Check memory cache
- Check disk cache (and promote to memory cache if found)
- Return nil if not found (caller should download from Firebase)
Cache key, typically the absolute URL string of the video.
Optional file extension to match the cached file.
Completion handler called with the cached data or nil if not found.
queryURLFromCache
Queries the local file path for a cached video. Synchronously checks if the file exists on disk.Cache key, typically the absolute URL string of the video.
Optional file extension to match the cached file.
Completion handler called with the file path string or nil if not found.
clearCache
Clears all cached data from both memory and disk. Returns the total size of cleared disk cache in MB.Completion handler called on the main thread with the size of cleared cache in MB.
SHA-2 Encryption
The cache manager uses SHA-256 hashing to encrypt cache keys for secure file naming. This ensures:- Security: Original URLs are not exposed in the file system
- Consistency: Same URL always maps to the same cache file
- Collision Resistance: Different URLs won’t overwrite each other
Cache Hierarchy
The caching system follows this hierarchy:- Memory Cache (NSCache): Fast access, limited by system memory
- Disk Cache (FileManager): Persistent storage in Documents/VideoCache
- Firebase Storage: Remote fallback when cache misses occur
Thread Safety
All cache operations are performed on a dedicated serial dispatch queue (com.VideoCache) to ensure thread safety and prevent race conditions during concurrent access.