Xcode 15中原有可用的URL Session代码失效问题求助
问题修复方案
1. 修复URLSession认证挑战的API误用问题
Xcode 15(对应iOS 17+)对URLSession的认证挑战代理逻辑做了强制要求:必须调用传入的completionHandler完成回调,不能再使用challenge.sender的相关方法,否则即使控制台有打印输出,也会触发API MISUSE错误,导致请求任务挂起。
修改你的代理方法如下:
func urlSession(_ session: URLSession, didReceive challenge: URLAuthenticationChallenge, completionHandler: @escaping (URLSession.AuthChallengeDisposition, URLCredential?) -> Void) { print("didRecieve URLAuthenticationChallenge") if challenge.protectionSpace.authenticationMethod == NSURLAuthenticationMethodServerTrust { print("handle Server Trust") guard let serverTrust = challenge.protectionSpace.serverTrust else { completionHandler(.cancelAuthenticationChallenge, nil) return } let credential = URLCredential(trust: serverTrust) completionHandler(.useCredential, credential) } else if challenge.protectionSpace.authenticationMethod == NSURLAuthenticationMethodHTTPBasic { print("handle HTTP Basic") let credentials = URLCredential(user: "username", password: "password", persistence: .forSession) completionHandler(.useCredential, credentials) } else if challenge.protectionSpace.authenticationMethod == NSURLAuthenticationMethodNTLM { print("handle NTLM") // 如需处理NTLM,同样通过completionHandler回调,示例: // completionHandler(.performDefaultHandling, nil) } else { print("perform default handling") completionHandler(.performDefaultHandling, nil) } }
2. 修复请求任务未启动的低级错误
你的代码中dataTask的resume缺少括号,导致方法未被调用,请求根本没有发起:
// 错误写法: // .resume // 正确写法: .resume()
3. 配置ATS例外以支持本地无证书HTTPS服务器
Xcode 15收紧了ATS安全策略,需要在Info.plist中添加针对目标IP的例外配置:
- 打开项目的
Info.plist文件 - 添加
App Transport Security Settings(NSAppTransportSecurity)字典 - 在该字典下添加
Exception Domains(NSExceptionDomains)字典 - 新增目标IP
192.168.17.254作为子字典,配置以下键值对:NSExceptionAllowsInsecureHTTPLoads:布尔值设为YESNSExceptionRequiresForwardSecrecy:布尔值设为NONSIncludesSubdomains:布尔值设为YESNSExceptionMinimumTLSVersion:字符串设为TLSv1.0(可根据服务器实际支持的TLS版本调整)
对应的plist源码格式:
<key>NSAppTransportSecurity</key> <dict> <key>NSExceptionDomains</key> <dict> <key>192.168.17.254</key> <dict> <key>NSExceptionAllowsInsecureHTTPLoads</key> <true/> <key>NSExceptionRequiresForwardSecrecy</key> <false/> <key>NSIncludesSubdomains</key> <true/> <key>NSExceptionMinimumTLSVersion</key> <string>TLSv1.0</string> </dict> </dict> </dict>
验证修复
完成以上修改后重新运行项目:
- 控制台不再出现
API MISUSE错误 dataTask的回调闭包可正常触发,能获取到请求数据或错误信息
内容的提问来源于stack exchange,提问作者Plasma
相关产品推荐
相关产品推荐

