URLSession auth challenge never called

I’m trying to access an API that’s demanding username/password credentials. My code is not correctly getting user credentials from user input and I’m receiving the error “Error copying matching creds. Error=-25300” with a status code “401”.

The postReq function looks like this:

func postRequest() {

    let parameters = ["grant_type=authorization_code&code=xyz"]
    
    guard let url = URL(string: "url to access") else {return}

    var request = URLRequest(url: url)
    
    request.httpMethod = "POST"
    request.addValue("xyz", forHTTPHeaderField: "X-API-Key")
    request.addValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type")
    request.addValue("Basic base64(xyz:xyz)", forHTTPHeaderField: "Authorization")
    guard let httpbody = try? JSONSerialization.data(withJSONObject: parameters, options: []) else {return}
    request.httpBody = httpbody
    
    let session = URLSession.shared.dataTask(with: request) { (data, response, error) in
        if let response = response {
            print(response)
        }
        if let data = data {
            do {
                let json = try JSONSerialization.jsonObject(with: data, options: [])
                print(json)
            } catch {
                print(error)
            }
        }
    }
    session.resume()
}

The delegate methods and helper method to get credentials look like this:

func urlSession(_ session: URLSession, task: URLSessionTask, didReceive challenge: URLAuthenticationChallenge, completionHandler: @escaping (URLSession.AuthChallengeDisposition, URLCredential?) -> Void) {
    let authMethod = challenge.protectionSpace.authenticationMethod
    guard authMethod == NSURLAuthenticationMethodHTTPBasic else {
        completionHandler(.performDefaultHandling, nil)
        return
    }
    //Call the completion handler
    guard let credential = credentialFromUI() else {
        completionHandler(.cancelAuthenticationChallenge, nil)
        return
    }
    completionHandler(.useCredential, credential)
}

func credentialFromUI() -> URLCredential? {
    guard let email = emailField!.text, !email.isEmpty,
        let password = passField!.text, !password.isEmpty else {
            return nil
    }
    return URLCredential(user: email, password: password, persistence: .forSession)
}

I’m having trouble getting user credentials from user input when accessing an API and receiving the error “Error copying matching creds. Error=-25300” with a status code “401”. My postReq function and the delegate methods and helper method to get credentials are provided.

The issue is that the code is not correctly getting user credentials from user input. The error “Error copying matching creds. Error=-25300” with a status code “401” is being received.

To fix this, make sure that the emailField and passField variables are correctly referencing the email and password input fields in the user interface. If they are not, update them to the correct references.

Additionally, make sure that the credentialFromUI() function is returning a valid URLCredential object. Check that the email and password fields are not empty and are being correctly passed into the URLCredential constructor.