关于我的问题,我参考了很多帖子。以下是我参考过的链接,
swift 5/XCode 12 版本中的基本身份验证失败。我在 xcode 中收到以下错误,
2021-07-08 15:28:32.693835+0200 App[43664:810014] Connection 1: encountered error(3:-9816)
2021-07-08 15:33:33.042464+0200 App[43664:821863] Connection 2: received failure notification
2021-07-08 15:33:33.042685+0200 App[43664:821863] Connection 2: failed to connect 3:-9816, reason -1
下面是我正在使用的代码(我正在使用 urlsession),
var mhUrlRequest = URLRequest(url: mhURL)
let userPasswordData = "username:password".data(using: .utf8)
let base64EncodedCredential = userPasswordData!.base64EncodedString(options: Data.Base64EncodingOptions.init(rawValue: 0))
let authString = "Basic \(base64EncodedCredential)"
mhUrlRequest.setValue(authString, forHTTPHeaderField: "Authorization")
我什至尝试了下面的代码
let config = URLSessionConfiguration.default
config.httpAdditionalHeaders = ["Authorization" : authString]
但这些似乎都不适合我。
将凭证转换为 Base64 并不是更好的方法。试试这些代码
let url = "your_url"
let usu_pass = "username:password"
var authData = (usu_pass.data(using: .utf8)?.base64EncodedString())!
let url = URL(string:url)
let header = [
"content-type" : "text/xml",
"Authorization" : "Basic " + authData
]
var request = URLRequest(url: url!)
request.allHTTPHeaderFields = header
request.httpMethod = "POST"
...