Skip to content

Commit

Permalink
Added a URLSession cache for remote data downloading
Browse files Browse the repository at this point in the history
When working with a tv series, I found that the loading of the
poster information for each tv episode re-loads ALL of the
posters for the series for each episode, even if the poster
data was the same for the previously selected episode.

Adding a URL cache to the URLSession to avoid re-downloading
(ive fixed the cache size to 128 meg) makes working with an
entire TV series a MUCH smoother experience.

For example, for a 'popular' tv series, seeing the first poster
for a selected search result might take 10-20 seconds
(as it was downloading 20-30 posters in the background before
displaying). For each episode in the series, it would re-download
the same URL data for the posters.  Adding the cache here means
it is only downloaded once.
  • Loading branch information
dagronf committed Apr 26, 2022
1 parent fe9ae07 commit ec5d74d
Showing 1 changed file with 20 additions and 2 deletions.
22 changes: 20 additions & 2 deletions Framework/src/RemoteData.swift
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,25 @@

import Foundation

fileprivate class RemoteCaching {
// Used a session that caches its results
static let remoteLoadSession: URLSession = {
// Create URL Session Configuration
let configuration = URLSessionConfiguration.default.copy() as! URLSessionConfiguration

// Set the in-memory cache to 128 MB
let cache = URLCache()
cache.memoryCapacity = 128 * 1024 * 1024
configuration.urlCache = cache

// Define Request Cache Policy
configuration.requestCachePolicy = .useProtocolCachePolicy
configuration.urlCache = cache

return URLSession(configuration: configuration)
}()
}

@objc public class RemoteData : NSObject {
private static let queue = DispatchQueue(label: "io.metaz.RemoteDataQueue")

Expand Down Expand Up @@ -97,8 +116,7 @@ import Foundation
if self.data == nil {
return;
}

URLSession.dataTask(url: url) { (d, resp, err) in
RemoteCaching.remoteLoadSession.dataTask(with: url) { (d, resp, err) in
if let error = err {
let info = [NSLocalizedDescriptionKey: error.localizedDescription]
let statusCode = (resp as? HTTPURLResponse)?.statusCode ?? 0
Expand Down

0 comments on commit ec5d74d

Please sign in to comment.