【问题标题】:How to Extract JSON Response Values Coming From PHP Backend in Swift iOS如何在 Swift iOS 中提取来自 PHP 后端的 JSON 响应值
【发布时间】: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&lt;Any&gt;' (aka 'DataResponse&lt;Any, AFError&gt;') has no member 'filepath'
  • @AqibJaved 我该怎么做?
  • 已经解码。你需要在resp上使用一个开关,如果成功,你可以将值转换为[String: Any],然后取回值...
  • @Larme 你能给出详细的答案/例子吗?

标签: php ios json swift httpresponse


【解决方案1】:

然后解码您的回复:

if let jsonResults = try JSONSerialization.jsonObject(with: data, options: []) as? [String: Any] {
    let filePath = jsonResults["filepath"] as? String // here is your value
}

【讨论】:

  • 如果在使用.responseJSON 时已经调用了JSONSerialization,为什么还要使用JSONSerialization?这是做两倍的工作......
【解决方案2】:

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 主要版本。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-09-01
    • 2021-08-12
    • 2020-05-08
    • 2020-03-10
    • 2014-11-24
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多