1

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

请在代码中帮助我。

将 UID 保存在LoginViewController

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


检索 UID RegistrationViewController


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

一直以来我都打算分开,为什么?我在哪里做错了。

4

1 回答 1

0

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

于 2019-11-04T09:38:59.810 回答