簡體   English   中英

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

[英]How to save one person UID globally to retrieve it in any ViewController in Swift

成功注冊后,我在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,
                      "password":passwordTextField.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, 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 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, 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 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()
    }
    }

一直以來我都打算分開,為什么? 我在哪里做錯了。

KeychainWrapper 不是保存用戶詳細信息的好方法。 最好使用“UserDefaults”的 go。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM