Why this happens
UIWebView does not keep a private cache. Every request it makes goes through the shared URLCache and every cookie lands in HTTPCookieStorage, both of which live for the lifetime of the process. When you call stopLoading() and release the web view, the rendered page goes away but the cached responses and cookies stay. That is why the memory figure in Activity Monitor or the Xcode debug navigator jumps once and then stays flat across later loads — you are seeing the shared cache fill up, not a leak in the view itself.
The second half of the surprise is that a new UIWebView instance appears to “remember” where you were, including a logged-in session. It is not state restoration; it is the same shared cache and cookie store being reused by the new instance.
One caveat before anything else: UIWebView has been deprecated since iOS 12 and App Review no longer accepts apps that use it. The fixes below apply to existing UIKit code, but new work should use WKWebView, which has its own data store and a different cleanup path (covered in step 4).
How to fix it
1. Purge the shared URL cache
This is the single call that recovers most of the memory. It drops every cached response the app has stored, in memory and on disk:
import Foundation
URLCache.shared.removeAllCachedResponses()
Call it when you leave the scene that hosted the web view, and again when the app receives a memory warning:
NotificationCenter.default.addObserver(
forName: UIApplication.didReceiveMemoryWarningNotification,
object: nil,
queue: .main
) { _ in
URLCache.shared.removeAllCachedResponses()
}
If you only want to evict one page, removeCachedResponse(for:) takes a URLRequest. Matching is by URL, so the request you pass must have the same URL as the one that was cached — which is why the blanket removeAllCachedResponses() is usually the practical choice.
2. Delete the cookies for that domain
Clearing the cache does not log the user out. Cookies are stored separately, and a stale session cookie is often what makes a fresh web view look like it kept its state.
import Foundation
func deleteCookies(for domain: String) {
guard let cookies = HTTPCookieStorage.shared.cookies else { return }
for cookie in cookies where cookie.domain.hasSuffix(domain) {
HTTPCookieStorage.shared.deleteCookie(cookie)
}
}
deleteCookies(for: "example.com")
Use hasSuffix rather than ==. Cookie domains are commonly stored with a leading dot (.example.com), so an equality check silently matches nothing.
3. Configure cache limits at launch instead of disabling caching
Setting the disk capacity to zero to “fix” the memory growth is a bad trade: every screen reloads from the network, and your users pay for it in latency and data. Configure realistic limits once at startup and purge on demand.
import UIKit
@main
class AppDelegate: UIResponder, UIApplicationDelegate {
func application(
_ application: UIApplication,
didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]? = nil
) -> Bool {
URLCache.shared.memoryCapacity = 4 * 1024 * 1024 // 4 MB
URLCache.shared.diskCapacity = 32 * 1024 * 1024 // 32 MB
return true
}
}
If you need the cache in a specific directory rather than the default location, build a replacement and assign it to URLCache.shared using the directory: initializer. Do this before any networking starts, because requests already in flight keep the old cache.
4. Tear down the web view in the right order
Releasing a UIWebView while it is still loading leaves the delegate callbacks and the page’s own memory hanging around longer than necessary. Do the cleanup in this order:
webView.stopLoading()
webView.delegate = nil
webView.loadHTMLString("", baseURL: nil) // drops the rendered page
webView.removeFromSuperview()
webView = nil
Loading an empty document is the part people skip. It forces the web view to discard the current page and its subresources before the object is deallocated.
5. If you have moved to WKWebView, clear its data store
WKWebView does not use URLCache the same way. Its storage lives in a WKWebsiteDataStore, and the web content runs in a separate process, so the memory number in Activity Monitor will not drop the instant you release the view.
import WebKit
func clearWebKitData(completion: @escaping () -> Void) {
let store = WKWebsiteDataStore.default()
let types = WKWebsiteDataStore.allWebsiteDataTypes()
let epoch = Date(timeIntervalSince1970: 0)
store.removeData(ofTypes: types, modifiedSince: epoch, completionHandler: completion)
}
For flows where nothing should persist at all — a checkout, a support chat, a shared kiosk — give the web view a non-persistent store instead of cleaning up afterwards:
let configuration = WKWebViewConfiguration()
configuration.websiteDataStore = .nonPersistent()
let webView = WKWebView(frame: .zero, configuration: configuration)
That store writes nothing to disk and is discarded with the web view.
How to prevent it
- Never set
diskCapacityto0as a memory fix; set a bounded limit and purge deliberately. - Clear the cache when leaving a heavy scene, not on every page load.
- Treat cookies as session state: delete them by domain suffix when the user logs out or finishes a flow.
- Subscribe to
UIApplication.didReceiveMemoryWarningNotificationand purge there as a safety net. - Plan the move to
WKWebView;UIWebViewis deprecated and will not be accepted by App Review. - When profiling, watch the WebContent process separately — a released web view’s memory is not always returned to your app’s footprint immediately.
FAQ
Does stopLoading() release the memory used by a UIWebView?
No. It cancels the in-flight request only. The cached responses, cookies and rendered page stay alive until the cache is purged and the view is torn down. Call removeAllCachedResponses() and load an empty document before releasing the view.
Why does the memory grow only on the first launch?
Because the growth is the shared URLCache filling up, not a per-instance leak. Once the cache holds the page’s resources, later loads are served from it and the footprint stays roughly flat. That flat line is the cache working as designed, not a bug.
Is it safe to call URLCache.shared.removeAllCachedResponses() from anywhere in the app?
It is safe but it is global: every image and API response your app cached is dropped, so the next requests go back to the network. Call it on the main thread at a natural boundary — leaving a screen, logging out, or handling a memory warning — rather than in the middle of an active download.
Parts of this guide are adapted from content licensed under CC BY-SA 3.0; this article is shared under the same license.