如何在 Swift iOS 中提取来自 PHP 后端的 JSON 响应值
How to Extract JSON Response Values Coming From PHP Backend in Swift iOS
我使用 almofire 上传了一张图片,它正在上传到我需要的正确路径。
但是,我需要将 PHP 后端代码中的一些响应放入我的 swift 中,例如 filepath
.
一张图片可以让我的问题更清楚和准确地了解我想从 .responseJSON
中得到什么
下图中是我对 PHP 代码的响应,我想获取 swift 中文件路径的值。我怎样才能做到这一点?
这是我的代码:
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")
}
然后解码您的回复:
if let jsonResults = try JSONSerialization.jsonObject(with: data, options: []) as? [String: Any] {
let filePath = jsonResults["filepath"] as? String // here is your value
}
responseJSON
块的值是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)")
}
}
现在,最好使用 Codable
结构来解析您的响应并调用 responseDecodable()
而不是使用 responseJSON()
,后者将使用 JSONSerialization
方法顺便说一句,已弃用,将在下一个 Alamofire 主要版本中删除。
我使用 almofire 上传了一张图片,它正在上传到我需要的正确路径。
但是,我需要将 PHP 后端代码中的一些响应放入我的 swift 中,例如 filepath
.
一张图片可以让我的问题更清楚和准确地了解我想从 .responseJSON
下图中是我对 PHP 代码的响应,我想获取 swift 中文件路径的值。我怎样才能做到这一点?
这是我的代码:
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")
}
然后解码您的回复:
if let jsonResults = try JSONSerialization.jsonObject(with: data, options: []) as? [String: Any] {
let filePath = jsonResults["filepath"] as? String // here is your value
}
responseJSON
块的值是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)")
}
}
现在,最好使用 Codable
结构来解析您的响应并调用 responseDecodable()
而不是使用 responseJSON()
,后者将使用 JSONSerialization
方法顺便说一句,已弃用,将在下一个 Alamofire 主要版本中删除。