Search code examples
iosswifturlsession

URLSessionDelegate class deinit not called


For client certificate authentication I've to use URLSessionDelegate in the custom class for handling all requests. The problem is the class is not deinitialize after a request made.

Code:

class Request: NSObject, URLSessionDelegate, URLSessionTaskDelegate{
    
    
    func request(){
        
        let url:URL = URL(string: "https://stackoverflow.com")!
        
        let config = URLSessionConfiguration.default
        
        
        
        URLSession(configuration: config, delegate: self, delegateQueue: .main).dataTask(with: url) { (data, response, error) in
            
            print("Received")
            
        }.resume()
    }
    
    func request2(){
        
        let url:URL = URL(string: "https://stackoverflow.com")!
        
        let config = URLSessionConfiguration.default
        
        
        URLSession(configuration: config).dataTask(with: url) { (data, response, error) in
            
            print("Received")
            
        }.resume()
    }
    
    deinit {
        print("Class deinit...")
    }
}

When calling Request().request() then deinit is not called. Calling Request().request2() then deinit is called.

I am not sure how to resolve this problem. Please help me to find out the solution. Thank you...


Solution

  • URLSession keeps a strong reference to its delegate (self in your case). Check the official documentation:

    The session object keeps a strong reference to the delegate until your app exits or explicitly invalidates the session. If you don’t invalidate the session, your app leaks memory until the app terminates.

    You can invalidate the session using its methods finishTasksAndInvalidate() or invalidateAndCancel(). After that URLSession will release the strong reference to its delegate.

    I guess you code example is just to demonstrate the behavior, but anyway I have to mention it's not a good practice to create a new URLSession for every single URLRequest.