我使用 almofire 上傳了一張圖片,它正在上傳到我需要的正確路徑。
但是,我需要將我的 PHP 后端代碼中的一些回應放入我的 swift 中,例如filepath.
一張圖片,讓我的問題更清楚、更準確地了解我想從.responseJSON
下圖中是我對 PHP 代碼的回應,我想快速獲取檔案路徑的值。我怎樣才能做到這一點?

這是我的代碼:
PHP:
<?php
if (empty($_FILES["image"])) {
$response = array("error" => "nodata");
}
else {
$response['error'] = "NULL";
$filename = uniqid() . ".jpg";
if (move_uploaded_file($_FILES['image']['tmp_name'], "../propertyImages/" . $filename)) {
$response['status'] = "success";
$response['filepath'] = "https://example.com/WebService/propertyImages/" . $filename;
$response['filename'] = "".$_FILES["file"]["name"];
} else{
$response['status'] = "Failure";
$response['error'] = "".$_FILES["image"]["error"];
$response['name'] = "".$_FILES["image"]["name"];
$response['path'] = "".$_FILES["image"]["tmp_name"];
$response['type'] = "".$_FILES["image"]["type"];
$response['size'] = "".$_FILES["image"]["size"];
}
}
echo json_encode($response);
?>
SWIFT代碼:
self.imageData = propImage.image!.jpegData(compressionQuality: 0.5)!
let headers: HTTPHeaders = [
"Content-type": "multipart/form-data"
]
AF.upload(
multipartFormData: { multipartFormData in
multipartFormData.append(self.imageData!, withName: "image" , fileName: "file.jpg", mimeType: "image/jpeg")
},
to:"https://example.com/WebService/api/uploadPropImage.php", method: .post , headers: headers)
.responseJSON { resp in
//let responseString: String = String(data: self.imageData!, encoding: .utf8)!
print(resp) //this prints all the responses from the PHP code, my problem is how do i get a specific response, such as the filepath only and so on?
}
編輯:
我嘗試了一些解決方案,這個似乎是可行的,但仍然給出錯誤讀數
"No exact matches in call to class method 'jsonObject'"
更新代碼:
AF.upload(multipartFormData: { multipartFormData in multipartFormData.append(self.imageData!, withName: "image" , fileName: "file.jpg", mimeType: "image/jpeg")}, to:"https://example.com/WebService/api/uploadPropImage.php", method: .post , headers: headers).responseJSON {
result in
do{
if let jsonResults = try JSONSerialization.jsonObject(with: result, options: []) as? [String: Any] { //error in this line
let filePath = jsonResults["filepath"] as? String
}
}catch{
print("ERROR")
}
uj5u.com熱心網友回復:
然后只需解碼您的回復:
if let jsonResults = try JSONSerialization.jsonObject(with: data, options: []) as? [String: Any] {
let filePath = jsonResults["filepath"] as? String // here is your value
}
uj5u.com熱心網友回復:
塊的值responseJSON是 a Result。這是一個經常使用的基本概念,因此您需要學習如何處理它。然后通常的做法是使用switch.
let headers: HTTPHeaders = ["Content-type": "multipart/form-data"]
AF.upload(multipartFormData: { multipartFormData in
multipartFormData.append(self.imageData!, withName: "image" , fileName: "file.jpg", mimeType: "image/jpeg")
},
to:"https://example.com/WebService/api/uploadPropImage.php", method: .post , headers: headers)
.responseJSON { result in
switch result {
case .success(let json):
guard let dictionary = json as? [String: Any] else { print("Response JSON is not a dictionary"); return }
guard let filePath = json["filePath"] as? String else { print("filePath key is not present in "\(json)" or is not a String"); return }
print("Filepath: \(filePath)")
case .failure(let error):
print("Error: \(error)")
}
}
現在,最好使用Codablestruct 來決議您的回應和呼叫responseDecodable(),而不是使用responseJSON()which will use JSONSerialization, 順便說一句已棄用并將在下一個 Alamofire 主要版本中洗掉的方法。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/421739.html
標籤:
