URLSessionDelegate usage

Hi everyone. I want to bind the URLSessionDelegate protocol with the custom protocol that it confirmed from URLSessionDelegate. But I can't catch its functions on the protocol. Can you tell me where I went wrong?

Answered by Kanan27 in 699050022
class ViewController: UIViewController {
   
  var delegate: SessionHelper?
   
  override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view.
   
    let request = URLRequest(url: URL(string: "https://www.google.com/")!)
     
    let session = URLSession(configuration: .ephemeral, delegate: delegate, delegateQueue: nil)
     
    session.dataTask(with: request) { data, response, error in
      if let error = error {
        print(error.localizedDescription)
      } else {
        // handle success request body
         
        if let _ = data {
          print("success data got.")
        }
      }
    }.resume()
  }
   
}
protocol SessionHelper: URLSessionDelegate {}

extension SessionHelper {
  func urlSession(_ session: URLSession, didReceive challenge: URLAuthenticationChallenge, completionHandler: @escaping (URLSession.AuthChallengeDisposition, URLCredential?) -> Void) {

    print("challenge")

  }
}

//class SessionHelper: NSObject, URLSessionDelegate {
//  func urlSession(_ session: URLSession, didReceive challenge: URLAuthenticationChallenge, completionHandler: @escaping (URLSession.AuthChallengeDisposition, URLCredential?) -> Void) {
//
//    print("challenge")
//
//  }
//}

Best to post your code in a code block (using Paste and Match Style). Then people may be able to help you.

Accepted Answer
class ViewController: UIViewController {
   
  var delegate: SessionHelper?
   
  override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view.
   
    let request = URLRequest(url: URL(string: "https://www.google.com/")!)
     
    let session = URLSession(configuration: .ephemeral, delegate: delegate, delegateQueue: nil)
     
    session.dataTask(with: request) { data, response, error in
      if let error = error {
        print(error.localizedDescription)
      } else {
        // handle success request body
         
        if let _ = data {
          print("success data got.")
        }
      }
    }.resume()
  }
   
}
protocol SessionHelper: URLSessionDelegate {}

extension SessionHelper {
  func urlSession(_ session: URLSession, didReceive challenge: URLAuthenticationChallenge, completionHandler: @escaping (URLSession.AuthChallengeDisposition, URLCredential?) -> Void) {

    print("challenge")

  }
}

//class SessionHelper: NSObject, URLSessionDelegate {
//  func urlSession(_ session: URLSession, didReceive challenge: URLAuthenticationChallenge, completionHandler: @escaping (URLSession.AuthChallengeDisposition, URLCredential?) -> Void) {
//
//    print("challenge")
//
//  }
//}

URLSessionDelegate usage
 
 
Q