-2

I'm using AlamoFire to communicate with my php/web-application and want to solve this annoying warning... My app is working fine but will become deprecated if i do not fix this.

.responseJSON { response in :

responseJSON(queue:dataPreprocessor:emptyResponseCodes:emptyRequestMethods:options:completionHandler:)' is deprecated: responseJSON deprecated and will be removed in Alamofire 6. Use responseDecodable instead.

public func authenticateUser(username: String, password: String, completion: @escaping (String) -> Void) {
        let url = "myAPI.com.br/api/Login"
        
        let parameters: Parameters = [
            "login": username,
            "password": password
        ]
        let headers: HTTPHeaders = [
            "Content-Type": "application/json"
        ]

        AF.request(url, method: .post, parameters: parameters, encoding: JSONEncoding.default, headers: headers)

        //FOR DEBUG ONLY
        //.validate()

            .responseJSON { response in

                //FOR DEBUG ONLY
               // print("Response JSON: \(response)")
                //print("Response Status Code: \(String(describing: response.response?.statusCode))")
                //print("Response HTTP Headers: \(String(describing: response.response?.allHeaderFields))")

                switch response.result {
                        //Em caso de sucesso na consulta -> retorno 200 -> salva o retorno da api dentro getContentFromAPI
                    case .success(let readContentFromAPI):

                        //Salva o conteudo retorno da api. Caso seja vazio cria dicionario padrão vazio
                        let savedDataFromAPI = (readContentFromAPI as? [String: Any]) ?? [:]

                        //Verifique se a API retornou success em status. /api/login -> echo json_encode(['status' => 'success', 'package' => $userData]);
                        if (savedDataFromAPI["status"] as? String == "success") {

                            //Armazena o dicionário tipo json ["Campo:Valor"] que retorna da api
                            let userPackage = savedDataFromAPI["userData"] as? [String: Any]

                            do {
                                //For save userData in application only
                                let data = try JSONSerialization.data(withJSONObject: userPackage!, options: .fragmentsAllowed)
                                let userData = try JSONDecoder().decode(UserData.self, from: data)

                                //Save userDate to application Session for later consulting
                                self.userData = userData

                                //Check if is a authorized user. If lvl 0, hold
                                //Only devs can change users groups
                                //This feature is a security feature
                                if (self.userData?.group_id == 0) {
                                    completion("Denied")
                                }
                                //Show homescreen if user is authorized
                                else {
                                    completion("Success")
                                }
                            } catch {
                                print("Error decoding user data: \(error)")
                            }
                        } else {
                            completion("Failure")
                        }

                    case .failure(let error):
                        completion("Error")
                        print("Request failed with error: \(error)")
                }
            }
    }

This is my API function:

public function login()
    {
        header('Content-Type: application/json');
        header('Access-Control-Allow-Origin: *');

        // Read POST request data
        $data = json_decode(file_get_contents('php://input'), true);
        $login = $data['login'];
        $hashedPass = $data['password'];

        $result = $this->model->authenticateUserAPI($login, $hashedPass);

        if ($result) {
            $userData = $this->model->loadAPISession($result);
            echo json_encode(['status' => 'success', 'userData' => $userData]);
        } else {
            echo json_encode(['status' => 'failed']);
        }
    }

I tried to change .responseJSON to .responseDATA and app stop to work like expected and another warning appears.

let savedDataFromAPI = (readContentFromAPI as? [String: Any]) ?? [:] -> Cast from 'Data' to unrelated type '[String : Any]' always fails

Any ideas how to fix this?

timbre timbre
  • 12,648
  • 10
  • 46
  • 77
  • 2
    Did you try `responseDecodable` as the warning suggests? – jnpdx Aug 28 '23 at 14:55
  • 1
    In recent Swift, it's recommended to use Codable struct. If you don't want to use modern features, you can still do manually with responseData, see https://stackoverflow.com/questions/70789753/update-responsejson-to-responsedecodable-in-swift/70804441#70804441 – Larme Aug 28 '23 at 14:58
  • If you replaced blindly `responseJSON` with `responseData`, then `readContentFromAPI` is a `Data`, so you need to serialize it with `JSONSerialization` first... – Larme Aug 28 '23 at 14:59

0 Answers0