如何设置保存状态并运行功能

时间:2019-01-10 00:10:46

标签: swift uinavigationcontroller appdelegate

我有3天的时间了,我找不到使保存状态运行功能的方法。

所以基本上这是我的保存状态

这是我在用户登录应用后写用户/驱动程序的方式,JSON返回用户/驱动程序密钥并为海底事件做准备
右波纹管

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()
    }


}

这是我编写密钥以准备驱动程序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获得调用,但没有运行该函数

0 个答案:

没有答案