@@ -21,6 +21,8 @@ public extension URLSession {
2121 public static var defaultTaskDelegate : URLSessionTaskDelegate ?
2222 public static var defaultLogger = Logger . networking
2323 public static var logBody : Bool = true
24+ /// Threshold for detect if response was from cache ( sec )
25+ public static var cacheDetectThreshold : TimeInterval = 0.05
2426
2527 public init ( ) { }
2628 }
@@ -45,28 +47,40 @@ public extension URLSession {
4547
4648 do {
4749
48- let ( data , urlResponse ) = try await data ( for: request, delegate : config . taskDelegate )
50+ let hasCachedResponse = configuration . urlCache ? . cachedResponse ( for: request) != nil
4951
52+ let start = CFAbsoluteTimeGetCurrent ( )
53+ let ( data, urlResponse) = try await data ( for: request, delegate: config. taskDelegate)
54+ let elapsed = CFAbsoluteTimeGetCurrent ( ) - start
5055
56+ let fromCache = hasCachedResponse && elapsed < Config . cacheDetectThreshold
5157 let respones = try urlResponse. httpResponse ( )
5258
5359 let dataResponse = DataResponse ( request: request,
5460 response: respones,
55- data: data)
61+ data: data,
62+ fromCache: fromCache,
63+ duration: elapsed)
5664
5765 let respBodyLog = config. logBody ? " \n \( dataResponse. bodyString) " : " "
58- config. logger? . debug ( " 🛬 \( dataResponse. request. urlString) \( dataResponse. status) \n \( respBodyLog) \n 📄 \( file. lastPathComponent) " )
66+ config. logger? . debug ( " 🛬 \( fromCache ? " (from cache) " : " " ) \( dataResponse. request. urlString) \( dataResponse. status) \n \( respBodyLog) \n 📄 \( file. lastPathComponent) " )
5967
6068 return dataResponse
6169 } catch {
70+ if let urlError = error as? URLError , urlError. code == . cancelled {
71+ config. logger? . debug ( " 🛬 (canceled) \( request. urlString) " )
72+ throw error
73+ } else if error is CancellationError {
74+ config. logger? . debug ( " 🛬 (canceled) \( request. urlString) " )
75+ throw error
76+ }
77+
6278 config. logger? . error ( " 🛬 \( request. urlString) \n \( error) " )
6379 throw error
6480 }
6581 }
6682}
6783
68-
69-
7084extension Data {
7185 var json : String ? {
7286 guard
0 commit comments