如何全局保存一个人的UID以在Swift中的任何ViewController中检索它

成功注册后,我在LoginViewController中获得UID。我正在将UID保存在LoginViewController中。并且我正在RegistrationViewController中检索UID。但是我在这里得到所有人的nil为什么?

请帮助我输入代码。

LoginViewController中保存UID:

func logInService(){

    let parameters = ["username":Int(userIdTextFielf.text ?? "") as Any,"imei_number":"","password":passwordTextField.text as Any,"name":"name"]

    let url = URL(string: "https://dev.com/webservices/login")
    var req =  URLRequest(url: url!)
    req.httpMethod = "POST"

    guard let httpBody = try? JSONSerialization.data(withJSONObject: parameters as Any,options: .prettyPrinted) else {return}
    req.httpBody = httpBody
    let session = URLSession.shared
    session.dataTask(with: req,completionHandler: {(data,response,error) in
        if response != nil {
            // print(response)
        }
        if let data = data {
            do{
                let json = try JSONSerialization.jsonObject(with: data,options: .mutableContainers) as! [String: Any]
                print("the json of loginnnnnn \(json)")
                self.Uid = json["id"] as? Int

                let emailL = json["user_email"] as? String
                KeychainWrapper.standard.set(emailL ?? "",forKey: "user_email")
                KeychainWrapper.standard.set(self.Uid!,forKey: "Uid")
                let saveUserId: Bool = KeychainWrapper.standard.set(self.Uid!,forKey: "Uid")

                DispatchQueue.main.async {

                    let mainStoryBoard = uistoryboard(name: "Main",bundle: nil)
                    let navigationController = mainStoryBoard.instantiateViewController(withIdentifier: "HomeNavigation")
                    let appDelagate = UIApplication.shared.delegate
                    appDelagate?.window??.rootViewController = navigationController

                }
            }catch{
                print("error")
            }
        }
    }).resume()
}


RegistrationViewController中检索UID:


  @IBaction func registerButton(_ sender: Any) {

        if (nameTextField.text ==  "" || phoneNumTextField.text == "" || passwordTextField.text ==  "" || conformPasswordTextField.text == "")
        {
            registerButton.isHidden = false
            sendOtpButton.isHidden = true
            AlertFun.ShowAlert(title: "Title",message: "RequiredAllFields",in: self)
        }
        else{
            registerButton.isHidden = true
            sendOtpButton.isHidden = false
            otpTextField.isHidden = false
            resendButn.isHidden = false
            DispatchQueue.main.async {
                self.otpTextField.text = self.otpField as? String
            }
            registerService()
            otpTimer = Timer.scheduledTimer(timeInterval: 1,target: self,selector: #selector(update),userInfo: nil,repeats: true)
        }
    }

    @IBaction func sendOTPButton(_ sender: Any) {
        otpService()
    }

    //MARK:- Service part
    @objc func registerService()
    {
    print("register tapped")

    let parameters = ["mobile_number": Int(phoneNumTextField.text ?? "") as Any,"email":emailTextField.text as Any,"name": nameTextField.text as Any]

    let url = URL(string: "https://dev.anyemi.com/webservices/anyemi/register")
    var req =  URLRequest(url: url!)
    req.httpMethod = "POST"

    guard let httpBody = try? JSONSerialization.data(withJSONObject: parameters,error) in
        if response != nil {
            // print(response)
        }
        if let data = data {
            do{
                let userId: Int? = KeychainWrapper.standard.integer(forKey: "Uid")
                print("login userid \(userId)")
                if userId != nil{
                    AlertFun.ShowAlert(title: "Title",message: "user exist",in: self)
                }
                else{
                    let json = try JSONSerialization.jsonObject(with: data,options: .mutableContainers) as! [String: Any]
                    print("the json regggggggggggis \(json)")
                    let phNum = json["mobile_number"] as? Int
                    let status = json["status"] as? String
                    self.otpField = json["otp"] as? Int
                }

            }catch{
                print("error")
            }
        }
    }).resume()
    }
    @objc func otpService(){

        let parameters = ["mobile_number": phoneNumTextField.text as Any,"otp": otpTextField.text as Any]
        let url = URL(string: "https://dev.com/webservices/otpverify")
        var req =  URLRequest(url: url!)
        req.httpMethod = "POST"

        guard let httpBody = try? JSONSerialization.data(withJSONObject: parameters,options: .prettyPrinted) else {return}
        req.httpBody = httpBody

        let session = URLSession.shared

        session.dataTask(with: req,error) in
            if response != nil {
                // print(response)
            }
            if let data = data {

                do{
                    let json = try JSONSerialization.jsonObject(with: data,options: .mutableContainers) as! [String: Any]
                    print("the json of otppppppppp \(json)")
                    DispatchQueue.main.async {
                        if (self.otpTextField.text == String(self.otpField ?? 12)){
                            print("registration successfullllll...")
                            let mobileNum = json["mobile_number"] as! [String : Any]
                            //self.Uid = mobileNum["id"] as? String
                            let name = mobileNum["name"] as? String
                            let phNum = mobileNum["username"] as? String
                            print("otp name \(String(describing: name))")
                            print("otp phnumber \(String(describing: phNum))")

                            let loginVC = self.storyboard?.instantiateViewController(withIdentifier: "LoginViewController") as! LoginViewController
                            self.present(loginVC,animated: true)
                        }
                        else if self.otpTextField.text == ""{
                            AlertFun.ShowAlert(title: "",message: "Please enter OTP",in: self)
                            print("register fail")
                        }
                        else {
                            AlertFun.ShowAlert(title: "",message: "Invalid OTP",in: self)
                            print("register fail")
                        }
                    }
                }catch{
                    print("error")
                }
            }
        }).resume()
    }
    }

我一直想去别的地方,为什么?我在哪里弄错了。

lixiaoxuaner 回答:如何全局保存一个人的UID以在Swift中的任何ViewController中检索它

KeychainWrapper不是保存用户详细信息的好方法。最好使用“ UserDefaults”。

本文链接:https://www.f2er.com/3167899.html

大家都在问