получение Cast из 'String' в несвязанный тип 'NSDictionary' всегда завершается неудачей в форме регистрации в Swift - PullRequest
0 голосов
/ 14 марта 2019

Я очень новичок в оболочке iOS, и я пытаюсь сделать приложение для регистрации с библиотекой Alamofire, это мой JSON.php

   <?php

//importing required script
require_once 'include/DbOperation.php';

$response = array();

if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    if (!verifyRequiredParams(array('userName','pass','sexo','edad','origen','motivo','visita','perfil'))) {
        //getting values
        $userName = $_POST['userName'];
        $pass = $_POST['pass'];
        $sexo = $_POST['sexo'];
        $edad = $_POST['edad'];
        $origen = $_POST['origen'];
        $motivo = $_POST['motivo'];
        $visita = $_POST['visita'];
        $perfil = $_POST['perfil'];

        //creating db operation object
        $db = new DbOperation();
        //adding user to database
        $result = $db->createUser($userName,$pass,$sexo,$edad,$origen,$motivo,$visita,$perfil);

        //making the response accordingly
        if ($result == USER_CREATED) {
            $response['error'] = false;
            $response['message'] = 'Usuario creado Exitosamente';
        } elseif ($result == USER_ALREADY_EXIST) {
            $response['error'] = true;
            $response['message'] = 'Usuario ya existente';
        } elseif ($result == USER_NOT_CREATED) {
            $response['error'] = true;
            $response['message'] = 'Ha ocurrido un error';
        }
    } else {
        $response['error'] = true;
        $response['message'] = 'Parametros no encontrados';
    }
} else {
    $response['error'] = true;
    $response['message'] = 'Solicitud invalida';
}

//function to validate the required parameter in request
function verifyRequiredParams($required_fields)
{

    //Getting the request parameters
    $request_params = $_REQUEST;

    //Looping through all the parameters
    foreach ($required_fields as $field) {
        //if any requred parameter is missing
        if (!isset($request_params[$field]) || strlen(trim($request_params[$field])) <= 0) {

            //returning true;
            return true;
        }
    }
    return false;
}

echo json_encode($response);echo json_encode($response);

, и это мой код Swift, он получаетподключение к серверу и регистрация пользователей, но когда я пытаюсь получить сообщение с результатом, я получаю сообщение об ошибке

//
//  Register.swift
//  ConoceTepic2.0
//
//  Created by ITIL9 on 04/03/19.
//  Copyright © 2019 ITIL9. All rights reserved.
//
import UIKit
import Alamofire
import SQLite3


class regUser: UIViewController, UIPickerViewDelegate, UIPickerViewDataSource{

    //Defined a constant that holds the URL for our web service
    let URL_REGISTER = "https://aleios.000webhostapp.com/aleWeb/Register.php"
    //
    let defaultValues = UserDefaults.standard

    @IBOutlet weak var label: UILabel!
    @IBOutlet weak var txtPassword: UITextField!
    @IBOutlet weak var txtSexo: UITextField!
    @IBOutlet weak var txtEdad: UITextField!
    @IBOutlet weak var txtUsuario: UITextField!


    @IBOutlet weak var dos: UITextField!
    @IBOutlet weak var uno: UITextField!
    @IBOutlet weak var tres: UITextField!

    var thePicker1 = UIPickerView()
    var thePicker2 = UIPickerView()
    var thePicker3 = UIPickerView()
    var thePicker4 = UIPickerView()

    let myPickerMotivo = [String](arrayLiteral: " ","Negocio", "Placer", "Compras")

    let myPickerEstado = [String](arrayLiteral: " ","Aguascalientes", "Baja California", "Baja California Sur", "Campeche", "CDMX", "Chiapas", "Chihuahua", "Coahuila", "Colima", "Durango", "Edo.Mex","Guanajuato","Guerrero","Hidalgo","Jalisco","Michoacan","Morelos","Nayarit", "Nuevo León", "Oaxaca", "Puebla”, “Querétaro","Quintana Roo","San Luis Potosí", "Sinaloa", "Tabasco", "Tamaulipas", "Tlaxcala", "Veracruz", "Yucatán", "Zacatecas", "Internacional")

    let myPickerVisita = [String](arrayLiteral: " ","Solo", "Pareja", "familia", "Compañero de trabajo")
    let myPickerSexo = [String](arrayLiteral: "","Femenino", "Masculino")

    override func viewDidLoad() {
        super.viewDidLoad()
        uno.inputView=thePicker1
        dos.inputView = thePicker2
        tres.inputView = thePicker3
        txtSexo.inputView = thePicker4

        thePicker1.delegate = self
        thePicker3.delegate = self
        thePicker2.delegate = self
        thePicker4.delegate = self

    }
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    //funciones para los selects

    func numberOfComponents(in pickerView: UIPickerView) -> Int {
        return 1
    }

    func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
        if (pickerView == thePicker1){
            return myPickerMotivo.count
        }else if (pickerView == thePicker2){
            return myPickerEstado.count
        }else if (pickerView == thePicker3){
            return myPickerVisita.count
        }else{
            return myPickerSexo.count
        }
    }


    func pickerView( _ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
        if (pickerView == thePicker1){
            return myPickerMotivo[row]
        }else if (pickerView == thePicker2){
            return myPickerEstado[row]
        }else if (pickerView == thePicker3){
            return myPickerVisita[row]
        }else{
            return myPickerSexo[row]
        }
    }

    func pickerView( _ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
        if (pickerView == thePicker1){
            uno.text=myPickerMotivo[row]
        }else if (pickerView == thePicker2){
            dos.text = myPickerEstado[row]
        }else if (pickerView == thePicker3){
            tres.text=myPickerVisita[row]
        }else{
            txtSexo.text = myPickerSexo[row]
        }
        self.view.endEditing(true)
    }

    @IBAction func btnEnvio(_ sender: UIButton) {

        var perfil: String
        var sex: String
        var selecM: String
        var selecV: String

        var edad: String

        var edad2:String
        edad2=txtEdad.text!
        sex = txtSexo.text!
        perfil=""
        selecM=uno.text!
        selecV=tres.text!

        if selecM == "Negocio" && selecV == "Pareja" {
            perfil = "3"
        }else if selecM == "Negocio" && selecV == "Familia"{
            perfil = "4"
        }else if selecM == "Negocio" && selecV == "Compañero de trabajo"{
            perfil = "5"
        }else if selecM == "Placer" && selecV == "Solo" && sex == "Femenino"{
            perfil = "7"
        }else if selecM == "Placer" && selecV == "Solo" && sex == "Masculino"{
            perfil = "6"
        }else if selecM == "Placer" && selecV == "Pareja" || selecM == "Placer" && selecV == "Familia"{
            perfil = "8"
        }else if selecM == "Placer" && selecV == "Compañero de trabajo" {
            perfil = "10"
        }else if selecM == "Compras" && selecV == "Solo" || selecM == "Compras" && selecV == "pareja" || selecM == "Compras" && selecV == "Compañero de trabajo" {
            perfil = "11"
        }else if selecM == "Compras" && selecV == "Familia"{
            perfil = "13"
        }else if selecM == "Negocio" && selecV == "Solo" && sex == "Femenino"{
            perfil = "2"
        }else if selecM == "Negocios" && selecV == "Solo" && sex == "Masculino"{
            perfil = "1"
        }else if edad2 == "65" {
            perfil = "14"
        }


        //isertTableUsuario(usu,pass)
        let parameters: Parameters=[
            "userName":txtUsuario.text!,
            "pass":txtPassword.text!,
            "sexo":txtSexo.text!,
            "edad":txtEdad.text!,
            "origen":dos.text!,
            "motivo":uno.text!,
            "visita":tres.text!,
            "perfil":perfil
        ]

        print("Valor parametros",parameters)
        //se envia la peticion http mediante el metodo post
        Alamofire.request(URL_REGISTER, method: .post, parameters: parameters,encoding: JSONEncoding.default).responseString{
            response in
            //Se muestran los resultados en la consola
            print(response)

            //se obtienen los valores desde el servidor
            if let result = response.result.value{
                print("Dentro del if result")
                //converting it as NSDictionary
               // let jsonData = result.object(at: 0) as! NSDictionary
                let jsonData = result as! NSDictionary //Here is where i get the next messge "Cast from 'String' to unrelated type 'NSDictionary' always fails"


                //displaying the message in label
                self.label.text = jsonData.value(forKey: "message") as! String?
            }
        }

        txtEdad.text = " "
        txtPassword.text = " "
        txtUsuario.text = " "
        txtSexo.text = " "
        dos.text = " "
        uno.text = " "
        tres.text = " "


    }
    }

1 Ответ

1 голос
/ 16 марта 2019

Я не уверен, поможет ли вам этот код, но это пример того, как вызвать REST API, используя Alamofire в Swift4.Это из книги, которую я рекомендую.Книга была написана Кристиной Моултон.Она очень помогает с ответами на вопросы (по электронной почте), которые могут возникнуть у вас во время работы над книгой.Вот ссылка на книгу: http://leanpub.com/iosappswithrest. Вот код:

let todoEndpoint = "https://jsonplaceholder.typicode.com/todos/1" 
Alamofire.request(todoEndpoint)
.responseJSON { response in
    // get errors
    if let error = response.result.error {
      print(error)
    }
    // get serialized data (i.e., JSON)
    if let value = response.result.value { 
        print(value)
    }
    // get raw data
    if let data = response.data { 
        print(data)
    }
    // get HTTPURLResponse
    if let httpResponse = response.response { 
        print(httpResponse)
    } 
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...