如何全局保存一个人的 UID 以在 Swift 的任何 ViewController 中检索它
Posted
技术标签:
【中文标题】如何全局保存一个人的 UID 以在 Swift 的任何 ViewController 中检索它【英文标题】:How to save one person UID globally to retrieve it in any ViewController in Swift 【发布时间】:2019-11-04 09:29:55 【问题描述】:注册成功后,我得到了LoginViewController
中的UID。我将 UID 保存在 LoginViewController
中。我正在RegistrationViewController
中检索 UID。但是在这里我为所有人收到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()
在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()
我总是要分手,为什么?我在哪里做错了。
【问题讨论】:
请分享您如何从登录导航到注册或登录后您做了什么? 您是否希望在卸载应用时也保存数据? @Sh_Khan,我需要检查用户是否已经存在或在注册时没有使用 uid...我想要.. 如果用户存在则提醒消息,如果不存在则完成详细信息我点击 regseterButn .. 这将发送 otp .. 进入 otp 后我点击 sendotpbutn ... 这将给出 uid ... 这与登录 uid 相同... 通过使用此 uid 我想在注册时检查用户是否存在.. . 【参考方案1】:KeychainWrapper 不是保存用户详细信息的好方法。最好使用“UserDefaults”。
【讨论】:
UserDefaults 或 KeychainWrapper 都是一样的..我已经更新了我的帖子..你能给帖子答案以上是关于如何全局保存一个人的 UID 以在 Swift 的任何 ViewController 中检索它的主要内容,如果未能解决你的问题,请参考以下文章
如何重新加载 UIPageViewController 以在 Swift 中重新加载其视图
我传递的变量不会仅获取视频用户 ID 和个人资料图片(Swift 3)
如何将 SKSpriteNode 合并到 SKTexture 以在 Swift 3 中形成新的 SKSpriteNode?