URLSession cache only












1















Sometimes I want to get data from the cache only when using URLSession. For example when quickly scrolling in a UITableView, I would like to show images that are already in the cache, but do not fire any HTTP requests. Images are just an example could be anything.



So I'm currently looking into URLSession's CachePolicy but it doesn't support an option to only get valid (not expired, etc) data from cache.



I can look into the URLCache myself, but this also of course returns data that might be expired. Is there some API that can validate a CachedURLResponse? Because then I can do it myself. Or do I have to implement the validating myself.










share|improve this question




















  • 2





    For Image Cache use SDWemImage Library

    – Manish Mahajan
    Nov 21 '18 at 9:23











  • @ManishMahajan Images are an example could be really anything.

    – Haagenti
    Nov 21 '18 at 9:45











  • @inokey I think this is not a duplicate to the link you provided. I have added Images as an example for a HTTP request. Could be really anything. Also in the link he uses an extra Dictionary to have them in memory. I would like to avoid this as URLSession already does this in URLCache.

    – Haagenti
    Nov 21 '18 at 9:47











  • @Haagenti try looking into 304 http status code. I remember I used it to determine whether or not I should get stuff from cache. Unfortunately I can't remember more specific.

    – inokey
    Nov 21 '18 at 9:50











  • @inokey Mmm not sure if 304 status code will do the trick because in the cache just contains the original response which will most likely be a 200 response.

    – Haagenti
    Nov 21 '18 at 15:33
















1















Sometimes I want to get data from the cache only when using URLSession. For example when quickly scrolling in a UITableView, I would like to show images that are already in the cache, but do not fire any HTTP requests. Images are just an example could be anything.



So I'm currently looking into URLSession's CachePolicy but it doesn't support an option to only get valid (not expired, etc) data from cache.



I can look into the URLCache myself, but this also of course returns data that might be expired. Is there some API that can validate a CachedURLResponse? Because then I can do it myself. Or do I have to implement the validating myself.










share|improve this question




















  • 2





    For Image Cache use SDWemImage Library

    – Manish Mahajan
    Nov 21 '18 at 9:23











  • @ManishMahajan Images are an example could be really anything.

    – Haagenti
    Nov 21 '18 at 9:45











  • @inokey I think this is not a duplicate to the link you provided. I have added Images as an example for a HTTP request. Could be really anything. Also in the link he uses an extra Dictionary to have them in memory. I would like to avoid this as URLSession already does this in URLCache.

    – Haagenti
    Nov 21 '18 at 9:47











  • @Haagenti try looking into 304 http status code. I remember I used it to determine whether or not I should get stuff from cache. Unfortunately I can't remember more specific.

    – inokey
    Nov 21 '18 at 9:50











  • @inokey Mmm not sure if 304 status code will do the trick because in the cache just contains the original response which will most likely be a 200 response.

    – Haagenti
    Nov 21 '18 at 15:33














1












1








1


1






Sometimes I want to get data from the cache only when using URLSession. For example when quickly scrolling in a UITableView, I would like to show images that are already in the cache, but do not fire any HTTP requests. Images are just an example could be anything.



So I'm currently looking into URLSession's CachePolicy but it doesn't support an option to only get valid (not expired, etc) data from cache.



I can look into the URLCache myself, but this also of course returns data that might be expired. Is there some API that can validate a CachedURLResponse? Because then I can do it myself. Or do I have to implement the validating myself.










share|improve this question
















Sometimes I want to get data from the cache only when using URLSession. For example when quickly scrolling in a UITableView, I would like to show images that are already in the cache, but do not fire any HTTP requests. Images are just an example could be anything.



So I'm currently looking into URLSession's CachePolicy but it doesn't support an option to only get valid (not expired, etc) data from cache.



I can look into the URLCache myself, but this also of course returns data that might be expired. Is there some API that can validate a CachedURLResponse? Because then I can do it myself. Or do I have to implement the validating myself.







swift nsurlsession foundation






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Nov 21 '18 at 11:31









ayaio

58.4k20132189




58.4k20132189










asked Nov 21 '18 at 9:13









HaagentiHaagenti

4,15032745




4,15032745








  • 2





    For Image Cache use SDWemImage Library

    – Manish Mahajan
    Nov 21 '18 at 9:23











  • @ManishMahajan Images are an example could be really anything.

    – Haagenti
    Nov 21 '18 at 9:45











  • @inokey I think this is not a duplicate to the link you provided. I have added Images as an example for a HTTP request. Could be really anything. Also in the link he uses an extra Dictionary to have them in memory. I would like to avoid this as URLSession already does this in URLCache.

    – Haagenti
    Nov 21 '18 at 9:47











  • @Haagenti try looking into 304 http status code. I remember I used it to determine whether or not I should get stuff from cache. Unfortunately I can't remember more specific.

    – inokey
    Nov 21 '18 at 9:50











  • @inokey Mmm not sure if 304 status code will do the trick because in the cache just contains the original response which will most likely be a 200 response.

    – Haagenti
    Nov 21 '18 at 15:33














  • 2





    For Image Cache use SDWemImage Library

    – Manish Mahajan
    Nov 21 '18 at 9:23











  • @ManishMahajan Images are an example could be really anything.

    – Haagenti
    Nov 21 '18 at 9:45











  • @inokey I think this is not a duplicate to the link you provided. I have added Images as an example for a HTTP request. Could be really anything. Also in the link he uses an extra Dictionary to have them in memory. I would like to avoid this as URLSession already does this in URLCache.

    – Haagenti
    Nov 21 '18 at 9:47











  • @Haagenti try looking into 304 http status code. I remember I used it to determine whether or not I should get stuff from cache. Unfortunately I can't remember more specific.

    – inokey
    Nov 21 '18 at 9:50











  • @inokey Mmm not sure if 304 status code will do the trick because in the cache just contains the original response which will most likely be a 200 response.

    – Haagenti
    Nov 21 '18 at 15:33








2




2





For Image Cache use SDWemImage Library

– Manish Mahajan
Nov 21 '18 at 9:23





For Image Cache use SDWemImage Library

– Manish Mahajan
Nov 21 '18 at 9:23













@ManishMahajan Images are an example could be really anything.

– Haagenti
Nov 21 '18 at 9:45





@ManishMahajan Images are an example could be really anything.

– Haagenti
Nov 21 '18 at 9:45













@inokey I think this is not a duplicate to the link you provided. I have added Images as an example for a HTTP request. Could be really anything. Also in the link he uses an extra Dictionary to have them in memory. I would like to avoid this as URLSession already does this in URLCache.

– Haagenti
Nov 21 '18 at 9:47





@inokey I think this is not a duplicate to the link you provided. I have added Images as an example for a HTTP request. Could be really anything. Also in the link he uses an extra Dictionary to have them in memory. I would like to avoid this as URLSession already does this in URLCache.

– Haagenti
Nov 21 '18 at 9:47













@Haagenti try looking into 304 http status code. I remember I used it to determine whether or not I should get stuff from cache. Unfortunately I can't remember more specific.

– inokey
Nov 21 '18 at 9:50





@Haagenti try looking into 304 http status code. I remember I used it to determine whether or not I should get stuff from cache. Unfortunately I can't remember more specific.

– inokey
Nov 21 '18 at 9:50













@inokey Mmm not sure if 304 status code will do the trick because in the cache just contains the original response which will most likely be a 200 response.

– Haagenti
Nov 21 '18 at 15:33





@inokey Mmm not sure if 304 status code will do the trick because in the cache just contains the original response which will most likely be a 200 response.

– Haagenti
Nov 21 '18 at 15:33












1 Answer
1






active

oldest

votes


















0














That's a fairly unusual request. Normally, you're either writing code to operate in an offline mode (in which case you want to pull from the cache whether the cached results are still valid or not) or you are online (in which case you want to fetch new data if it isn't valid).



I would encourage you to really think long and hard about whether you really want to force cache validation if you aren't firing network requests.



That said, if you really want that behavior, there are two ways you can do it:




  • Use NSURLRequestReturnCacheDataDontLoad and validate the age of the cached response yourself.

  • Perform the request in a custom session, use NSURLRequestUseProtocolCachePolicy, and in that session, install a custom NSURLProtocol subclass that overrides initWithTask:cachedResponse:client: and startLoading, and calls URLProtocol:didFailWithError: on the provided client at the top of its startLoading method.


The second approach is probably the best option, because you don't have to worry about knowing all the esoteric rules for cache validation. By making the actual load fail, the cache will work normally, but as soon as it actually would start making a network request, your custom protocol prevents that from happening. And because you'll register the protocol only in that specific session (via the protocolClasses array on the session configuration), it won't break networking in other sessions.






share|improve this answer


























  • NSURLRequestReturnCacheDataDontLoad : "Use existing cache data, regardless or age or expiration date, and fail if no cached data is available". I would like only data when its valid.

    – Haagenti
    Dec 2 '18 at 21:05













  • Ah. I misread your question. I'll update my answer.

    – dgatwood
    Dec 3 '18 at 4:44











  • Updated. The custom protocol approach is slightly more complex, but still a lot simpler than cache validation. :-)

    – dgatwood
    Dec 3 '18 at 4:57











  • I will implement your second approach which also sounds to me like the best option. Thank you.

    – Haagenti
    Dec 3 '18 at 6:55











  • You might find that this ends up working the same way as pulling everything from the cache. If so, then the only option is #1.

    – dgatwood
    Dec 3 '18 at 18:40











Your Answer






StackExchange.ifUsing("editor", function () {
StackExchange.using("externalEditor", function () {
StackExchange.using("snippets", function () {
StackExchange.snippets.init();
});
});
}, "code-snippets");

StackExchange.ready(function() {
var channelOptions = {
tags: "".split(" "),
id: "1"
};
initTagRenderer("".split(" "), "".split(" "), channelOptions);

StackExchange.using("externalEditor", function() {
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled) {
StackExchange.using("snippets", function() {
createEditor();
});
}
else {
createEditor();
}
});

function createEditor() {
StackExchange.prepareEditor({
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader: {
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
},
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
});


}
});














draft saved

draft discarded


















StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53408631%2furlsession-cache-only%23new-answer', 'question_page');
}
);

Post as a guest















Required, but never shown

























1 Answer
1






active

oldest

votes








1 Answer
1






active

oldest

votes









active

oldest

votes






active

oldest

votes









0














That's a fairly unusual request. Normally, you're either writing code to operate in an offline mode (in which case you want to pull from the cache whether the cached results are still valid or not) or you are online (in which case you want to fetch new data if it isn't valid).



I would encourage you to really think long and hard about whether you really want to force cache validation if you aren't firing network requests.



That said, if you really want that behavior, there are two ways you can do it:




  • Use NSURLRequestReturnCacheDataDontLoad and validate the age of the cached response yourself.

  • Perform the request in a custom session, use NSURLRequestUseProtocolCachePolicy, and in that session, install a custom NSURLProtocol subclass that overrides initWithTask:cachedResponse:client: and startLoading, and calls URLProtocol:didFailWithError: on the provided client at the top of its startLoading method.


The second approach is probably the best option, because you don't have to worry about knowing all the esoteric rules for cache validation. By making the actual load fail, the cache will work normally, but as soon as it actually would start making a network request, your custom protocol prevents that from happening. And because you'll register the protocol only in that specific session (via the protocolClasses array on the session configuration), it won't break networking in other sessions.






share|improve this answer


























  • NSURLRequestReturnCacheDataDontLoad : "Use existing cache data, regardless or age or expiration date, and fail if no cached data is available". I would like only data when its valid.

    – Haagenti
    Dec 2 '18 at 21:05













  • Ah. I misread your question. I'll update my answer.

    – dgatwood
    Dec 3 '18 at 4:44











  • Updated. The custom protocol approach is slightly more complex, but still a lot simpler than cache validation. :-)

    – dgatwood
    Dec 3 '18 at 4:57











  • I will implement your second approach which also sounds to me like the best option. Thank you.

    – Haagenti
    Dec 3 '18 at 6:55











  • You might find that this ends up working the same way as pulling everything from the cache. If so, then the only option is #1.

    – dgatwood
    Dec 3 '18 at 18:40
















0














That's a fairly unusual request. Normally, you're either writing code to operate in an offline mode (in which case you want to pull from the cache whether the cached results are still valid or not) or you are online (in which case you want to fetch new data if it isn't valid).



I would encourage you to really think long and hard about whether you really want to force cache validation if you aren't firing network requests.



That said, if you really want that behavior, there are two ways you can do it:




  • Use NSURLRequestReturnCacheDataDontLoad and validate the age of the cached response yourself.

  • Perform the request in a custom session, use NSURLRequestUseProtocolCachePolicy, and in that session, install a custom NSURLProtocol subclass that overrides initWithTask:cachedResponse:client: and startLoading, and calls URLProtocol:didFailWithError: on the provided client at the top of its startLoading method.


The second approach is probably the best option, because you don't have to worry about knowing all the esoteric rules for cache validation. By making the actual load fail, the cache will work normally, but as soon as it actually would start making a network request, your custom protocol prevents that from happening. And because you'll register the protocol only in that specific session (via the protocolClasses array on the session configuration), it won't break networking in other sessions.






share|improve this answer


























  • NSURLRequestReturnCacheDataDontLoad : "Use existing cache data, regardless or age or expiration date, and fail if no cached data is available". I would like only data when its valid.

    – Haagenti
    Dec 2 '18 at 21:05













  • Ah. I misread your question. I'll update my answer.

    – dgatwood
    Dec 3 '18 at 4:44











  • Updated. The custom protocol approach is slightly more complex, but still a lot simpler than cache validation. :-)

    – dgatwood
    Dec 3 '18 at 4:57











  • I will implement your second approach which also sounds to me like the best option. Thank you.

    – Haagenti
    Dec 3 '18 at 6:55











  • You might find that this ends up working the same way as pulling everything from the cache. If so, then the only option is #1.

    – dgatwood
    Dec 3 '18 at 18:40














0












0








0







That's a fairly unusual request. Normally, you're either writing code to operate in an offline mode (in which case you want to pull from the cache whether the cached results are still valid or not) or you are online (in which case you want to fetch new data if it isn't valid).



I would encourage you to really think long and hard about whether you really want to force cache validation if you aren't firing network requests.



That said, if you really want that behavior, there are two ways you can do it:




  • Use NSURLRequestReturnCacheDataDontLoad and validate the age of the cached response yourself.

  • Perform the request in a custom session, use NSURLRequestUseProtocolCachePolicy, and in that session, install a custom NSURLProtocol subclass that overrides initWithTask:cachedResponse:client: and startLoading, and calls URLProtocol:didFailWithError: on the provided client at the top of its startLoading method.


The second approach is probably the best option, because you don't have to worry about knowing all the esoteric rules for cache validation. By making the actual load fail, the cache will work normally, but as soon as it actually would start making a network request, your custom protocol prevents that from happening. And because you'll register the protocol only in that specific session (via the protocolClasses array on the session configuration), it won't break networking in other sessions.






share|improve this answer















That's a fairly unusual request. Normally, you're either writing code to operate in an offline mode (in which case you want to pull from the cache whether the cached results are still valid or not) or you are online (in which case you want to fetch new data if it isn't valid).



I would encourage you to really think long and hard about whether you really want to force cache validation if you aren't firing network requests.



That said, if you really want that behavior, there are two ways you can do it:




  • Use NSURLRequestReturnCacheDataDontLoad and validate the age of the cached response yourself.

  • Perform the request in a custom session, use NSURLRequestUseProtocolCachePolicy, and in that session, install a custom NSURLProtocol subclass that overrides initWithTask:cachedResponse:client: and startLoading, and calls URLProtocol:didFailWithError: on the provided client at the top of its startLoading method.


The second approach is probably the best option, because you don't have to worry about knowing all the esoteric rules for cache validation. By making the actual load fail, the cache will work normally, but as soon as it actually would start making a network request, your custom protocol prevents that from happening. And because you'll register the protocol only in that specific session (via the protocolClasses array on the session configuration), it won't break networking in other sessions.







share|improve this answer














share|improve this answer



share|improve this answer








edited Dec 3 '18 at 4:56

























answered Dec 2 '18 at 5:09









dgatwooddgatwood

8,16012044




8,16012044













  • NSURLRequestReturnCacheDataDontLoad : "Use existing cache data, regardless or age or expiration date, and fail if no cached data is available". I would like only data when its valid.

    – Haagenti
    Dec 2 '18 at 21:05













  • Ah. I misread your question. I'll update my answer.

    – dgatwood
    Dec 3 '18 at 4:44











  • Updated. The custom protocol approach is slightly more complex, but still a lot simpler than cache validation. :-)

    – dgatwood
    Dec 3 '18 at 4:57











  • I will implement your second approach which also sounds to me like the best option. Thank you.

    – Haagenti
    Dec 3 '18 at 6:55











  • You might find that this ends up working the same way as pulling everything from the cache. If so, then the only option is #1.

    – dgatwood
    Dec 3 '18 at 18:40



















  • NSURLRequestReturnCacheDataDontLoad : "Use existing cache data, regardless or age or expiration date, and fail if no cached data is available". I would like only data when its valid.

    – Haagenti
    Dec 2 '18 at 21:05













  • Ah. I misread your question. I'll update my answer.

    – dgatwood
    Dec 3 '18 at 4:44











  • Updated. The custom protocol approach is slightly more complex, but still a lot simpler than cache validation. :-)

    – dgatwood
    Dec 3 '18 at 4:57











  • I will implement your second approach which also sounds to me like the best option. Thank you.

    – Haagenti
    Dec 3 '18 at 6:55











  • You might find that this ends up working the same way as pulling everything from the cache. If so, then the only option is #1.

    – dgatwood
    Dec 3 '18 at 18:40

















NSURLRequestReturnCacheDataDontLoad : "Use existing cache data, regardless or age or expiration date, and fail if no cached data is available". I would like only data when its valid.

– Haagenti
Dec 2 '18 at 21:05







NSURLRequestReturnCacheDataDontLoad : "Use existing cache data, regardless or age or expiration date, and fail if no cached data is available". I would like only data when its valid.

– Haagenti
Dec 2 '18 at 21:05















Ah. I misread your question. I'll update my answer.

– dgatwood
Dec 3 '18 at 4:44





Ah. I misread your question. I'll update my answer.

– dgatwood
Dec 3 '18 at 4:44













Updated. The custom protocol approach is slightly more complex, but still a lot simpler than cache validation. :-)

– dgatwood
Dec 3 '18 at 4:57





Updated. The custom protocol approach is slightly more complex, but still a lot simpler than cache validation. :-)

– dgatwood
Dec 3 '18 at 4:57













I will implement your second approach which also sounds to me like the best option. Thank you.

– Haagenti
Dec 3 '18 at 6:55





I will implement your second approach which also sounds to me like the best option. Thank you.

– Haagenti
Dec 3 '18 at 6:55













You might find that this ends up working the same way as pulling everything from the cache. If so, then the only option is #1.

– dgatwood
Dec 3 '18 at 18:40





You might find that this ends up working the same way as pulling everything from the cache. If so, then the only option is #1.

– dgatwood
Dec 3 '18 at 18:40




















draft saved

draft discarded




















































Thanks for contributing an answer to Stack Overflow!


  • Please be sure to answer the question. Provide details and share your research!

But avoid



  • Asking for help, clarification, or responding to other answers.

  • Making statements based on opinion; back them up with references or personal experience.


To learn more, see our tips on writing great answers.




draft saved


draft discarded














StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53408631%2furlsession-cache-only%23new-answer', 'question_page');
}
);

Post as a guest















Required, but never shown





















































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown

































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown







Popular posts from this blog

How to change which sound is reproduced for terminal bell?

Can I use Tabulator js library in my java Spring + Thymeleaf project?

Title Spacing in Bjornstrup Chapter, Removing Chapter Number From Contents