如何在应用启动时清除缓存?解决PDF切换显示旧文件问题
Absolutely, clearing the cache every time your app starts is a perfect fix for this stale PDF issue—let’s walk through how to implement this based on your platform/tech stack:
Why This Happens First
Most PDF viewers (native or web-based) cache downloaded files to speed up future loads. But when you’re switching PDFs frequently, especially if URLs are reused or the viewer holds onto cached entries, you’ll end up seeing old content instead of the updated PDF. Starting fresh with a clean cache on app launch eliminates this problem entirely.
For Android Apps
If you’re using Android’s built-in PdfRenderer or libraries like AndroidPdfViewer, target the app’s cache directory where PDFs are stored:
- Grab the cache path with
context.getCacheDir()(internal) orcontext.getExternalCacheDir()(external) - Delete only PDF files on app launch (to avoid wiping other important cached data)
- Example Kotlin snippet (put this in your
Applicationclass'sonCreate()):
override fun onCreate() { super.onCreate() clearPDFCache(this) } private fun clearPDFCache(context: Context) { val cacheDirs = listOf(context.cacheDir, context.externalCacheDir) cacheDirs.forEach { dir -> dir?.listFiles()?.forEach { file -> if (file.name.lowercase().endsWith(".pdf")) { file.delete() } } } }
Pro tip: Check your third-party library docs—some (like AndroidPdfViewer) have a built-in clearCache() method on the viewer instance that’s even easier to use.
For iOS Apps
For PDFKit or libraries like PSPDFKit, clear the app’s cache directory on launch:
- Access the cache folder via
FileManager.default.urls(for: .cachesDirectory, in: .userDomainMask).first - Delete only PDF files to preserve other cached assets
- Example Swift snippet (add to
application(_:didFinishLaunchingWithOptions:)):
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool { clearPDFCache() return true } private func clearPDFCache() { guard let cacheDir = FileManager.default.urls(for: .cachesDirectory, in: .userDomainMask).first else { return } do { let cachedFiles = try FileManager.default.contentsOfDirectory(at: cacheDir, includingPropertiesForKeys: nil) for file in cachedFiles where file.pathExtension.lowercased() == "pdf" { try FileManager.default.removeItem(at: file) } } catch { print("Oops, failed to clear PDF cache: \(error.localizedDescription)") } }
Note: Many third-party iOS PDF libraries have dedicated cache-clearing APIs—check their docs to avoid reinventing the wheel.
For Web/JavaScript Apps
If you’re using pdf.js or a web-based viewer, you have two solid options:
- Cache-busting URLs: Append a unique timestamp (e.g.,
?t=${Date.now()}) to your PDF URLs when loading them—this forces the browser to fetch the fresh file instead of using cache. - Clear cache via Cache API: Delete cached PDF entries on app initialization:
async function clearPDFCache() { const allCaches = await caches.keys(); for (const cacheName of allCaches) { const cache = await caches.open(cacheName); const cachedRequests = await cache.keys(); for (const request of cachedRequests) { if (request.url.endsWith('.pdf')) { await cache.delete(request); } } } } // Run this when your web app loads clearPDFCache();
Bonus: Alternative (No Full Cache Clear)
If you don’t want to wipe all PDF cache on startup, try:
- Using unique cache keys/filenames for each PDF (even if URLs are similar)
- Forcing the viewer to bypass cache with request headers (e.g.,
Cache-Control: no-cachewhen downloading PDFs)
内容的提问来源于stack exchange,提问作者BestRazer

