Как сделать состояние сохранения и запустить функцию - PullRequest
0 голосов
/ 10 января 2019

У меня есть эта проблема в течение 3 дней, я не могу найти способ заставить мое состояние сохранения запустить функцию.

так что в основном это мое состояние сохранения

так я пишу user / driver после входа пользователя в приложение, JSON возвращает user / driver KEY и готовится к seague
правый сильфон

if emailcapturado == emailText {

(для удобного расположения **)

@IBAction func iniciarSesion(_ sender: UIButton) {

        guard
            let emailText = Email.text, !emailText.isEmpty,
            let contrasenaText = Contrasena.text, !contrasenaText.isEmpty else
        {
            displayAlert(title: "Información Faltante", message: "Debes porporcionar un correo y contraseña")
            return
        }

        let myURL = URL(string: "hehe") 
        var request = URLRequest(url: myURL!) 
        request.httpMethod = "POST"
        let posString = "Email=\(emailText)&Password=\(contrasenaText)" 
        request.httpBody = posString.data(using: .utf8)
        let task = URLSession.shared.dataTask(with: request) {
            data, response, error in

            if let error = error {
                 DispatchQueue.main.async {
                 self.displayAlert(title: "Usuario", message: "Error de conexion")
                }
                print("error=\(error)")
                return
            }

            guard let data = data else {
                 DispatchQueue.main.async {
                 self.displayAlert(title: "Usuario", message: "Error de conexion")
                }
                print("Something wrong")
                return
            }


            struct Blog: Decodable {
                let Response: String
                let articles: [Article]

                enum CodingKeys : String, CodingKey {
                    case Response

                    case articles = "Perfil"
                }
            }

            struct Article: Decodable {
                let id: String
                let Nombre: String
                let Email: String
                let Telefono: String
                let Email_Contacto: String
                let Telefono_Contacto: String
                let Nivel: String
                let Foto: String?
                let Ciudad: String?
                let Direccion: String?
                let Matricula: String?
                let Licencia: String?
                let N_Taxi: String?
                let Tipo_Vehiculo: String?
                let Marca_Vehiculo: String?
                let Year: String?
            }



            do {


                let blog = try JSONDecoder().decode(Blog.self, from: data)


                DispatchQueue.main.async {
                    if blog.Response == "true" {

                        UserDefaults.standard.set(self.Email.text!, forKey: "emailUser")
                        UserDefaults.standard.set(self.Contrasena.text!, forKey: "contrasenaUser")
                        for article in blog.articles {
                            let emailcapturado = article.Email
                            let tipoNivel = article.Nivel






                            if emailcapturado == emailText {

                                if tipoNivel == "0" {
                                    UserDefaults.standard.set(article.id, forKey: "idUser")
                                    UserDefaults.standard.set(article.Nombre, forKey: "nombrePasajero")
                                    UserDefaults.standard.set(article.Email, forKey: "emailPasajero")
                                    UserDefaults.standard.set(article.Telefono, forKey: "telefonoPasajero")
                                    UserDefaults.standard.set(article.Email_Contacto, forKey: "emailContactoPasajero")
                                    UserDefaults.standard.set(article.Telefono_Contacto, forKey: "telefonoContactoPasajero")
                                    UserDefaults.standard.set(article.Nivel, forKey: "nivelUser")//USER KEY saves 0
                                    UserDefaults.standard.synchronize()
                                        self.performSegue(withIdentifier: "logeadoSegue", sender: nil)
                                } else if tipoNivel == "1" {
                                    // 1 es chofer
                                    UserDefaults.standard.set(article.id, forKey: "idChofer")
                                    UserDefaults.standard.set(article.Nombre, forKey: "nombreChofer")
                                    UserDefaults.standard.set(article.Email, forKey: "emailChofer")
                                    UserDefaults.standard.set(article.Telefono, forKey: "telefonoChofer")
                                    UserDefaults.standard.set(article.Email_Contacto, forKey: "emailContactoChofer")
                                    UserDefaults.standard.set(article.Telefono_Contacto, forKey: "telefonoContactoChofer")
                                    UserDefaults.standard.set(article.Foto, forKey: "fotoChofer")
                                    UserDefaults.standard.set(article.Ciudad, forKey: "ciudadChofer")
                                    UserDefaults.standard.set(article.Direccion, forKey: "direccionChofer")
                                    UserDefaults.standard.set(article.Matricula, forKey: "matriculaChofer")
                                    UserDefaults.standard.set(article.Licencia, forKey: "licenciaChofer")
                                    UserDefaults.standard.set(article.N_Taxi, forKey: "numeroTaxiChofer")
                                    UserDefaults.standard.set(article.Tipo_Vehiculo, forKey: "tipoVehiculoChofer")
                                    UserDefaults.standard.set(article.Marca_Vehiculo, forKey: "marcaVehiculoChofer")
                                    UserDefaults.standard.set(article.Year, forKey: "yearChofer")
                                    UserDefaults.standard.set(article.Nivel, forKey: "nivelChofer")//Driver KEY gets save '1'
                                    UserDefaults.standard.synchronize()
                                        self.performSegue(withIdentifier: "choferSegue", sender: nil)
                                } else {
                                    print("Invalid tipoNivel:", tipoNivel)
                                }
                                break
                            }
                        }
                    } else if  blog.Response == "false" {
                         DispatchQueue.main.async {
                        self.displayAlert(title: "Usuario", message: "Contraseña/Email incorrecto")
                        }
                    } else if  blog.Response == "nothing" {
                         DispatchQueue.main.async {
                        self.displayAlert(title: "Información", message: "Usuario no existe")
                        }
                    }


                }
            } catch {
                 DispatchQueue.main.async {
                self.displayAlert(title: "Usuario", message: "Error de conexion")
                }
                print("Error: Couldn't decode data into Blog:", error)
                return
            }
        }
        task.resume()

    }

делегат приложения:

    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
check()
checkuser()
}

функции для проверки моих значений предыдущего набора в AppDelegate

 func check() {
    if UserDefaults.standard.value(forKey: "nivelChofer") != nil
    {
        let VC = UIStoryboard(name: "Main", bundle: Bundle.main).instantiateViewController(withIdentifier: "ConductorPrincipalViewController")
        let navVC = UINavigationController(rootViewController: VC)
        let share = UIApplication.shared.delegate as? AppDelegate
        share?.window?.rootViewController = navVC
        share?.window?.makeKeyAndVisible()
    }


}

func checkuser() {
    if UserDefaults.standard.value(forKey: "nivelUser") != nil
    {
        let VC = UIStoryboard(name: "Main", bundle: Bundle.main).instantiateViewController(withIdentifier: "UnaVezLogeadoViewController")
        let navVC = UINavigationController(rootViewController: VC)
        let share = UIApplication.shared.delegate as? AppDelegate
        share?.window?.rootViewController = navVC
        share?.window?.makeKeyAndVisible()
    }


}

так я пишу KEY для подготовки к сохранению состояния в VC драйвера "" ConductorPrincipalViewController "" (для удобного расположения)

if blog.Response == "1" {

прямо под

@objc func consultarViaje(){

    let idcho = UserDefaults.standard.string(forKey: "idChofer")

    let myURL = URL(string: "hee hee")
    var request = URLRequest(url: myURL!)
    request.httpMethod = "POST"
    let posString = "ID_Conductor=\(idcho!)"
    request.httpBody = posString.data(using: .utf8)
    let task = URLSession.shared.dataTask(with: request) {
        data, response, error in

        if let error = error {
            print("error=\(error)")
            return
        }

        guard let data = data else {
            print("Something wrong")
            return
        }

        struct Blog: Decodable {
            let Response: String
            let articles: [Article]

            enum CodingKeys : String, CodingKey {
                case Response = "Response"

                case articles = "Perfil"
            }
        }

        struct Article: Decodable {


        }

        do {
            let blog = try JSONDecoder().decode(Blog.self, from: data)

            // si el pasajero acepta el viaje se queda guardado el PUNTO DONDE EL CONDUCTOR VAA IR POR EL PASAJERO JEJE y es igual a 1
            //
            DispatchQueue.main.async {
                if blog.Response == "1" {
                    self.displayAlert(title: "Información..", message: "¡El pasajero aceptó!")
                    UserDefaults.standard.set("1", forKey: "saveState")// KEY FOR SAVE POINT 
                    print("el pasajero acepto")
                    self.helloWorldTimer2?.invalidate()
                    self.helloWorldTimer2 = nil
                    self.enviarCotizacion.isHidden = true
                    self.cotizacionUitext.isHidden = true
                    self.accionEnviar.isHidden = true
                    self.irAlPasajero.isHidden = false


                }
                else if (blog.Response == "0")
                {
                    print("esperando..")

                }
                    else if (blog.Response == "2")
                {
                    self.displayAlert(title: "Información..", message: "El pasajero canceló la solicitud")
                    print("el pasajero rechazo")
                    self.helloWorldTimer2?.invalidate()
                    self.helloWorldTimer2 = nil
                    self.enviarCotizacion.isHidden = true
                    self.cotizacionUitext.text = ""
                    self.cotizacionUitext.isHidden = true
                    self.accionEnviar.isHidden = true
                    let allAnnotations = self.map.annotations
                    self.map.removeAnnotations(allAnnotations)
                    self.map.removeOverlays(self.map.overlays)
                    self.helloWorldTimer = Timer.scheduledTimer(timeInterval: 30.0, target: self, selector: #selector(ConductorPrincipalViewController.ConsultarSolicitudes), userInfo: nil, repeats: true)

                }
                else {
                    print("error")
                    self.displayAlert(title: "ERROR..", message: "ERROR")
                }

            }
        }

        catch {
            print("Error: Couldn't decode data into Blog:", error)
            print(error)
            return

        }

    }
    task.resume()
}

так что я пытаюсь сделать внутри моего "ConductorPrincipalViewController" VC это сделать эту функцию для запуска ЕСЛИ пользователь закроет приложение (состояние сохранения)

func saveState()
{
    let oli = UserDefaults.standard.value(forKey: "saveState") as!     String
    if (oli == "1")
    {

        self.helloWorldTimer2?.invalidate()
        self.helloWorldTimer2 = nil
        self.enviarCotizacion.isHidden = true
        self.cotizacionUitext.isHidden = true
        self.accionEnviar.isHidden = true
        self.irAlPasajero.isHidden = false

    }



}

Я попытался сделать еще одну функцию в AppDelegate для вызова saveState ()

func checkSaveStatechofer()
{
    if UserDefaults.standard.value(forKey: "saveState") != nil
    {
        let VC = UIStoryboard(name: "Main", bundle: Bundle.main).instantiateViewController(withIdentifier: "ConductorPrincipalViewController")
        let navVC = UINavigationController(rootViewController: VC)
        let share = UIApplication.shared.delegate as? AppDelegate
        share?.window?.rootViewController = navVC
        share?.window?.makeKeyAndVisible()
    }
}

не работает. Функциональные вызовы AppDelegate checkSaveStatechofer ()

let VC = UIStoryboard(name: "Main", bundle: Bundle.main).instantiateViewController(withIdentifier: "ConductorPrincipalViewController")

VC получает вызов, но без запуска функции

...