嘿,所以我是Swift的新手,我已经成功地从公共API提取了数据,但是还有一个需要身份验证。我确实有一个帐户,并且已经验证了凭据是否有效,但是我不清楚如何使用基本身份验证写POST请求
我在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()
}
}
答案 0 :(得分:0)
对于基本身份验证,请将身份验证数据放在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"