嘿,我对Swift还比较陌生,我已经成功地从公共API获取了数据,但还有一个需要身份验证。我确实有一个帐户,我已经验证了凭据是否有效,但我不清楚如何使用Basic Auth 编写POST请求
我在Basic Auth的Wiki页面上看到,它说要与用户配置URL&像这样传递:https://Aladdin:OpenSesame@www.example.com/index.html,但仅凭这一点并不能解决问题,因此我不确定还需要做些什么来配置此请求。任何帮助都将不胜感激!
struct Response: Codable {
var results: [Result]
}
struct Result: Codable {
var pool_system_type: String
}
struct WaterTestView: View {
@State private var results = [Result]()
var body: some View {
List(results, id: .trackId) { result in
VStack(alignment: .leading) {
Text(result.pool_system_type)
}
}.onAppear(perform: loadData)
}
func loadData() {
guard let url = URL(string: "https://myemail@email.com:mypassword@biolabhydra.com/api/v3/water_tests") else {
print("Invalid URL")
return
}
let request = URLRequest(url: url)
URLSession.shared.dataTask(with: request) { data, response, error in
if let data = data {
if let decodedResponse = try? JSONDecoder().decode(Response.self, from: data) {
DispatchQueue.main.async {
results = decodedResponse.results
}
return
}
}
print("Fetch failed: (error?.localizedDescription ?? "Unknown error")")
}.resume()
}
}
对于基本身份验证,您将身份验证数据放在HTTP头字段中。
extension URLRequest {
mutating func setBasicAuth(username: String, password: String) {
let encodedAuthInfo = String(format: "%@:%@", username, password)
.data(using: String.Encoding.utf8)!
.base64EncodedString()
addValue("Basic (encodedAuthInfo)", forHTTPHeaderField: "Authorization")
}
}
var request = URLRequest(url: URL(string: "https://www.awesome.com/")!)
request.setBasicAuth(username: "awesomeUser", password: "awesomePass")
request.httpMethod = "POST"