Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does try? Data(contentsOf: URL) use caching?

I'm seeing an issue where I'm running the below multiple times with different URLs, and I'm getting the same data back 'sometimes' (it seems random). I'm wondering if iOS is caching some pages and giving me back the same data and not actually going to the URL.

Is there a cache? If so, is there a way to clear it before each call?

if let dataString = try? Data(contentsOf: url!) {
    let pageContent = String(data: dataString, encoding: String.Encoding.utf8)
}
like image 370
FlatDog Avatar asked Sep 06 '19 17:09

FlatDog


People also ask

What is URL cache?

The URLCache class implements the caching of responses to URL load requests, by mapping NSURLRequest objects to CachedURLResponse objects. It provides a composite in-memory and on-disk cache, and lets you manipulate the sizes of both the in-memory and on-disk portions.

What is Nscache in iOS?

A mutable collection you use to temporarily store transient key-value pairs that are subject to eviction when resources are low. iOS 4.0+ iPadOS 4.0+ macOS 10.6+ Mac Catalyst 13.1+ tvOS 9.0+ watchOS 2.0+


1 Answers

Take a look at init(contentsOf:options:) which provides an option called NSData.ReadingUncached. That's evidence that the simple form is cached and an answer to how you can control whether its cached.

A better approach with even more control is via URLSession

like image 138
danh Avatar answered Sep 24 '22 23:09

danh