@@ -18,6 +18,7 @@ open class URLSessionClient: NSObject, URLSessionDelegate, URLSessionTaskDelegat
1818 case sessionBecameInvalidWithoutUnderlyingError
1919 case dataForRequestNotFound( request: URLRequest ? )
2020 case networkError( data: Data , response: HTTPURLResponse ? , underlying: Error )
21+ case sessionInvalidated
2122
2223 public var errorDescription : String ? {
2324 switch self {
@@ -29,6 +30,8 @@ open class URLSessionClient: NSObject, URLSessionDelegate, URLSessionTaskDelegat
2930 return " URLSessionClient was not able to locate the stored data for request \( String ( describing: request) ) "
3031 case . networkError( _, _, let underlyingError) :
3132 return " A network error occurred: \( underlyingError. localizedDescription) "
33+ case . sessionInvalidated:
34+ return " Attempting to create a new request after the session has been invalidated! "
3235 }
3336 }
3437 }
@@ -44,6 +47,12 @@ open class URLSessionClient: NSObject, URLSessionDelegate, URLSessionTaskDelegat
4447 /// The raw URLSession being used for this client
4548 open private( set) var session : URLSession !
4649
50+ private var hasBeenInvalidated = Atomic < Bool > ( false )
51+
52+ private var hasNotBeenInvalidated : Bool {
53+ !self . hasBeenInvalidated. value
54+ }
55+
4756 /// Designated initializer.
4857 ///
4958 /// - Parameters:
@@ -61,6 +70,7 @@ open class URLSessionClient: NSObject, URLSessionDelegate, URLSessionTaskDelegat
6170 ///
6271 /// NOTE: This must be called from the `deinit` of anything holding onto this client in order to break a retain cycle with the delegate.
6372 public func invalidate( ) {
73+ self . hasBeenInvalidated. value = true
6474 func cleanup( ) {
6575 self . session = nil
6676 self . clearAllTasks ( )
@@ -107,6 +117,11 @@ open class URLSessionClient: NSObject, URLSessionDelegate, URLSessionTaskDelegat
107117 open func sendRequest( _ request: URLRequest ,
108118 rawTaskCompletionHandler: RawCompletion ? = nil ,
109119 completion: @escaping Completion ) -> URLSessionTask {
120+ guard self . hasNotBeenInvalidated else {
121+ completion ( . failure( URLSessionClientError . sessionInvalidated) )
122+ return URLSessionTask ( )
123+ }
124+
110125 let task = self . session. dataTask ( with: request)
111126 let taskData = TaskData ( rawCompletion: rawTaskCompletionHandler,
112127 completionBlock: completion)
0 commit comments