提问人:Alexander Chebotarev 提问时间:6/9/2023 最后编辑:Alexander Chebotarev 更新时间:6/10/2023 访问量:95
如何正确提出发布请求
How to correctly make post request
问:
我需要用我的数据提出发布请求。此外,它还需要 access_token 标头。现在,我将描述我的后请求的完整结构。我必须发送需要字符串的描述。要发送的数据取自 descriptionTextView。Photo 接受我从 photoButton 中的 imagePicker 上传的文件。Rate 需要字典。数据取自 rateInputView { “可用性”: 1, “美女”:2, 纯度:3 } Report_status 始终接受字符串“Accepted”。Type_obj 接受一个字符串,并取决于我在 pickerView 中选择的内容(route、event、place)。id_obj获取我从 searchBar 中保存的对象的 ID。还应该有一个“结果”字段。此处为该结构:[{ “waste_id”:{“name”: “大写字母”, “unit_of_waste”: “件”}, 数量: 10 }] 它从 wasteInputView 的文本字段中获取值,以及该 wasteInputView 中 Label 的名称。
我试图做到这一点,但我有一个错误:无法解析 JSON:错误域 = NSCocoaErrorDomain 代码 = 3840 “JSON 文本未以数组或对象开头,并且允许未设置片段的选项。在第 1 行第 0 列附近。UserInfo={NSDebugDescription=JSON 文本未以数组或对象开头,并允许未设置片段的选项。
我该如何解决?这是我的代码:
@objc func postActionButton() {
// Check if access token is available
guard let accessToken = UserDefaults.standard.string(forKey: "AccessToken") else {
print("Access token is missing")
return
}
// Prepare the URL
guard let url = URL(string: "\(apiLink)/report/create_report/") else {
print("Invalid URL")
return
}
// Prepare the request
var request = URLRequest(url: url)
request.httpMethod = "POST"
// Set the access token in the header
request.setValue("Bearer \(accessToken)", forHTTPHeaderField: "Authorization")
// Prepare the data for the request body
guard let image = selectedImage else {
print("No image selected")
return
}
guard let imageData = image.jpegData(compressionQuality: 0.8) else {
print("Failed to convert image to data")
return
}
let base64Image = imageData.base64EncodedString()
// Create the request body
let parameters: [String: Any] = [
"photo": base64Image,
"description": descriptionTextView.text ?? "",
"rate": [
"availability": rateInputView.transportTextField.text ?? "",
"beauty": rateInputView.beautyTextField.text ?? "",
"purity": rateInputView.pollutionTextField.text ?? ""
],
"report_status": "Accepted",
"type_obj": selectedOption ?? "",
"id_obj": selectedOptionID ?? 0,
"Results": [
[
"waste_id": [
"name": wasteInputView.wasteLabel.text ?? "",
"unit_of_waste": "kg"
],
"amount": wasteInputView.bulbTextField.text ?? ""
] as [String : Any]
]
]
do {
request.httpBody = try JSONSerialization.data(withJSONObject: parameters, options: [])
} catch {
print("Failed to create JSON data: \(error)")
return
}
let task = URLSession.shared.dataTask(with: request) { data, response, error in
if let error = error {
print("Request error: \(error)")
return
}
guard let data = data else {
print("No data received")
return
}
do {
if let json = try JSONSerialization.jsonObject(with: data, options: []) as? [String: Any] {
// Process the response JSON
print("Response JSON: \(json)")
}
} catch {
print("Failed to parse JSON: \(error)")
}
}
task.resume()
}
答: 暂无答案
上一个:功能首次超出范围
评论
print("Response str: \(String(data: data, encoding: .utf8)")
看看你实际收到了什么。可能是错误消息,也可能只是其他格式的响应,因为您没有将所需的 JSON 放在 accept 标头中request.addValue("application/json", forHTTPHeaderField: "Accept")