URLSession delegates methods not being called

Hi,

I've followed lots of solutions on stackoverflow, tutorials and even the apple documentation but I can't figure out why my URLSession delegates methods are not called


Here is the code I use :


public class RestRequestor : NSObject,   URLSessionTaskDelegate   {
    var receivedData: Data?
//   private var session : URLSession?
  
    private lazy var session: URLSession = {
        let configuration = URLSessionConfiguration.default
        configuration.waitsForConnectivity = true
        return URLSession(configuration: configuration,
                          delegate: self, delegateQueue: nil)
    }()
  
    public func startLoad() {
      
        let url = URL(string: "http://www.lefigaro.fr")!
        receivedData = Data()
        let task = session.dataTask(with: url)
        task.resume()
    }
  
    func urlSession(_ session: URLSession, taskIsWaitingForConnectivity task: URLSessionTask) {
        print("On attend quelque chose")
    }
  
    func urlSession(_ session: URLSession, didBecomeInvalidWithError error: Error?) {
        print("Là il y a comme un problème")
    }
  
    func urlSession(_ session: URLSession, dataTask: URLSessionDataTask, didReceive data: Data) {
        print("on a reçu quelque chose")
    }
  
  
    func urlSession(_ session: URLSession, task: URLSessionTask, didCompleteWithError error: Error?) {
        print("Ouf c'est fini")
    }
  
  
    func urlSession(_ session: URLSession, dataTask: URLSessionDataTask, didReceive response: URLResponse, completionHandler: @escaping (URLSession.ResponseDisposition) -> Void) {
        print("on commence a recevoir quelquechose")
        completionHandler(.allow)
    }
  
}

and then I call


@IBActionfunc runthisone(_ sender:Any){
        let titi = RestRequestor.init()
       
        titi.startLoad()
    }




I'm struggling with this one for 2 days without knowing what to do


Does anyone have an idea ?

Replies

What version of Xcode are you using? When I pasted your code into a new project, created with Xcode 10.1, it produces a raft of compiler warnings like Instance method '***' nearly matches optional requirement 'yyy' of protocol 'URLSessionTaskDelegate', which implies that you’re either using an old version of Xcode or you’re using the wrong function signature for your delegate callbacks.

Share and Enjoy

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

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

I have the same problem, my delegate methods dons't call never. I am using XCODE 10.1 and Swift 4


This is my Delegate class

import Foundation

class NSURLSessionPinningDelegate: NSObject, URLSessionDelegate {
    
    func urlSession(_ session: URLSession, didReceive challenge: URLAuthenticationChallenge, completionHandler: @escaping (URLSession.AuthChallengeDisposition, URLCredential?) -> Swift.Void) {
        
        if (challenge.protectionSpace.authenticationMethod == NSURLAuthenticationMethodServerTrust) {
            if let serverTrust = challenge.protectionSpace.serverTrust {
                var secresult = SecTrustResultType.invalid
                let status = SecTrustEvaluate(serverTrust, &secresult)
                
                if(errSecSuccess == status) {
                    if let serverCertificate = SecTrustGetCertificateAtIndex(serverTrust, 0) {
                        let serverCertificateData = SecCertificateCopyData(serverCertificate)
                        let data = CFDataGetBytePtr(serverCertificateData);
                        let size = CFDataGetLength(serverCertificateData);
                        let cert1 = NSData(bytes: data, length: size)
                        let file_der = Bundle.main.path(forResource: "certificate", ofType: "der")
                        
                        if let file = file_der {
                            if let cert2 = NSData(contentsOfFile: file) {
                                if cert1.isEqual(to: cert2 as Data) {
                                    completionHandler(URLSession.AuthChallengeDisposition.useCredential, URLCredential(trust:serverTrust))
                                    return
                                }
                            }
                        }
                    }
                }
            }
        }
        
        // Pinning failed
        completionHandler(URLSession.AuthChallengeDisposition.cancelAuthenticationChallenge, nil)
    }
    
}



This is my implementation in my method to use it


let session = URLSession(
                configuration: URLSessionConfiguration.ephemeral,
                delegate: NSURLSessionPinningDelegate(),
                delegateQueue: OperationQueue.main)
            
            
            let task = session.dataTask(with: request, completionHandler: { (data, response, error) -> Void in
                if error != nil {
                    print("error: \(error!.localizedDescription): \(error!)")
                } else if data != nil {
                    if let str = NSString(data: data!, encoding: String.Encoding.utf8.rawValue) {
                        print("Received data:\n\(str)")
                    } else {
                        print("Unable to convert data to text")
                    }
                }
            })
            
            task.resume()


This is my Info.plist


<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
  <key>CFBundleDevelopmentRegion</key>
  <string>Spain</string>
  <key>CFBundleExecutable</key>
  <string>$(EXECUTABLE_NAME)</string>
  <key>CFBundleIdentifier</key>
  <string>$(PRODUCT_BUNDLE_IDENTIFIER)</string>
  <key>CFBundleInfoDictionaryVersion</key>
  <string>6.0</string>
  <key>CFBundleName</key>
  <string>$(PRODUCT_NAME)</string>
  <key>CFBundlePackageType</key>
  <string>APPL</string>
  <key>CFBundleShortVersionString</key>
  <string>1.0</string>
  <key>CFBundleVersion</key>
  <string>1</string>
  <key>LSRequiresIPhoneOS</key>
  <true/>
  <key>NSAppTransportSecurity</key>
  <dict>
  <key>NSAllowsArbitraryLoads</key>
  <true/>
  </dict>
  <key>NSCameraUsageDescription</key>
  <string>Necesitamos acceder a la cámara para realizar el escaneo de tarjetas.</string>
  <key>UILaunchStoryboardName</key>
  <string>LaunchScreen</string>
  <key>UIMainStoryboardFile</key>
  <string>Main</string>
  <key>NSPhotoLibraryUsageDescription</key>
  <string>Necesitamos acceder a la galería para poder realizar la carga de imágenes.</string>
  <key>UIRequiredDeviceCapabilities</key>
  <array>
  <string>armv7</string>
  </array>
  <key>UIStatusBarHidden</key>
  <true/>
  <key>UISupportedInterfaceOrientations</key>
  <array>
  <string>UIInterfaceOrientationPortrait</string>
  </array>
  <key>UISupportedInterfaceOrientations~ipad</key>
  <array>
  <string>UIInterfaceOrientationPortrait</string>
  <string>UIInterfaceOrientationPortraitUpsideDown</string>
  <string>UIInterfaceOrientationLandscapeLeft</string>
  <string>UIInterfaceOrientationLandscapeRight</string>
  </array>
  <key>UIViewControllerBasedStatusBarAppearance</key>
  <false/>
</dict>
</plist>