NSURLSession does not call delegate method

Hi,


I am running below code to send request within URLSession data task, but the delegate methods are not called, but get called if I change to other url, for example "https://m1.m.dm/dp/authServices.htm".


class ViewController: UIViewController {
    
    var receivedData: Data?
    
    private lazy var session: URLSession = {
        let configuration = URLSessionConfiguration.default
        configuration.waitsForConnectivity = true
        return URLSession(configuration: configuration,
                          delegate: self, delegateQueue: nil)
    }()

    override func viewDidLoad() {
        super.viewDidLoad()

        startLoad()
    }

    func startLoad() {

        let url = URL(string: "https://m5.m.dm/dp/authServices.htm")!//delegate never called by URLSession
        let task = session.dataTask(with: url)
        task.resume()
    }

}

extension ViewController: URLSessionDelegate, URLSessionTaskDelegate, URLSessionDataDelegate {
    
    // MARK: - URLSessionTaskDelegate

    func urlSession(_ session: URLSession, task: URLSessionTask, didCompleteWithError error: Error?) {
        
    }
    
    // MARK: URLSessionDataDelegate
    
    func urlSession(_ session: URLSession, dataTask: URLSessionDataTask, didReceive response: URLResponse, completionHandler: @escaping (URLSession.ResponseDisposition) -> Void) {
        completionHandler(.allow)
    }
    
    
    func urlSession(_ session: URLSession, dataTask: URLSessionDataTask, didReceive data: Data) {
        
    }
    
}

Replies

That’s because you’ve set

waitsForConnectivity
and the host you’re connecting to,
m5.m.dm
, is not found.
URLSession
is waiting for the network conditions to change such that this host becomes available. For example, the user might start a VPN connection that gives the iOS device access to the
m.dm
domain.

If you implement the

urlSession(_:taskIsWaitingForConnectivity:)
delegate method, you’ll find that it’s called almost immediately to notify you of this delay.

Share and Enjoy

Quinn “The Eskimo!”
Apple Developer Relations, Developer Technical Support, Core OS/Hardware

let myEmail = "eskimo" + "1" + "@apple.com"