【发布时间】:2022-01-26 09:30:25
【问题描述】:
我使用 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")
}
【问题讨论】:
-
尝试打印(rep.filepath)
-
@AqibJaved 这是我收到的错误消息,
Value of type 'AFDataResponse<Any>' (aka 'DataResponse<Any, AFError>') has no member 'filepath' -
@AqibJaved 我该怎么做?
-
已经解码。你需要在
resp上使用一个开关,如果成功,你可以将值转换为[String: Any],然后取回值... -
@Larme 你能给出详细的答案/例子吗?
标签: php ios json swift httpresponse