以前有效的 URL 会话代码在 Xcode 15 中不再有效

问题描述 投票:0回答:1

这段代码在过去几年中运行良好,但在清理旧项目后,它不再在 Xcode 15 中运行。我正确设置了“URLSessionDelegate”,下面是一个简化的方法:

'''

    let user = "user"
    let pass = "pass"
    let token = "123456"
    let url = "https://192.168.17.254:7443/api/auth/login"

    let authUrl = URL(string: url)
    var authRequest = URLRequest(url: authUrl)
    authRequest.httpMethod = "POST"
    
    let authBody = ["username": user, "password": pass, "token": token]
    authRequest.httpBody = try! JSONSerialization.data(withJSONObject: authBody, options: .prettyPrinted)
    
    authRequest.setValue("application/json", forHTTPHeaderField: "Content-Type")
    authRequest.setValue("TOKEN=", forHTTPHeaderField: "Cookie")
    
    let authSessionConfig = URLSessionConfiguration.default
    let authSession = URLSession(configuration: authSessionConfig, delegate: self, delegateQueue: nil)
    authSession.dataTask(with: authRequest) { (data, response, error) in

            //Never reaches code here, no error no data

    }.resume
        

'''

我还有“didReceive Challenge”的代表,我已经尝试了这里其他问题的几个版本..

'''

func urlSession(_ session: URLSession, didReceive challenge: URLAuthenticationChallenge, completionHandler: @escaping (URLSession.AuthChallengeDisposition, URLCredential?) -> Void) {
    print("didRecieve URLAuthenticationChallenge")
    
    if challenge.protectionSpace.authenticationMethod == NSURLAuthenticationMethodServerTrust  {
        print("send credential Server Trust")
        let credential = URLCredential(trust: challenge.protectionSpace.serverTrust!)
        challenge.sender!.use(credential, for: challenge)
        
    }else if challenge.protectionSpace.authenticationMethod == NSURLAuthenticationMethodHTTPBasic{
        print("send credential HTTP Basic")
        let defaultCredentials: URLCredential = URLCredential(user: "username", password: "password", persistence:URLCredential.Persistence.forSession)
        challenge.sender!.use(defaultCredentials, for: challenge)
        
    }else if challenge.protectionSpace.authenticationMethod == NSURLAuthenticationMethodNTLM{
        print("send credential NTLM")
        
    } else{
        challenge.sender!.performDefaultHandling!(for: challenge)
    }
}

'''

正如我所说,这之前工作得很好,但现在我收到 API MISUSE 错误,并且它推断完成处理程序没有被调用,即使它被调用了,正如您可以在输出中看到 print 语句。

enter image description here

我正在连接到在端口 7443 上使用 HTTPS 但没有任何证书等的本地 Web 服务器,我考虑发布一个示例项目,但如果没有本地 Web 服务器,您将无法重现它。我怀疑 Xcode 15 中存在一些新的 ATS 安全性,但我不知道它要我做什么来修复它。

swift xcode url urlsession
1个回答
0
投票

此代码不正确:

    challenge.sender!.use(credential, for: challenge)

这里也轮不到你打电话

use()
。由您决定调用完成处理程序(这就是错误所说的)。

您想要的代码是:

completionHandler(.useCredential, credential)

对于函数的其他部分也是如此。

有关完整详细信息,请参阅处理身份验证质询

© www.soinside.com 2019 - 2024. All rights reserved.