ios - 如何在我的 iOS 应用程序(Swift 5)中检查 Google 身份验证状态
问题描述
当用户向 Google 进行身份验证时,我想在某处记录用户的状态。当用户单击单元格时,我希望如果用户通过身份验证,那么我想将他发送到另一个视图,如果没有,则将他发送到授权页面。但我做不到。我创建了一个标志,但由于某种原因,它仅在重新启动应用程序后才会触发。
...
protocol SourceViewControllerDelegate{
func requestReloadTable()
}
class SourcesViewController: UIViewController, GIDSignInDelegate {
...
var isAuthenticationComplete: GIDAuthentication?
...
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: SourceCell.reuseId, for: indexPath) as! SourceCell
cell.sourceViewControllerDelegate = self
....
return cell
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
tableView.deselectRow(at: indexPath, animated: true)
if isAuthenticationComplete != nil {
let storyboard = UIStoryboard(name: "GoogleDriveViewController", bundle: nil)
let vc = storyboard.instantiateViewController(identifier: "GoogleDrive") as! GoogleDriveViewController
navigationController?.pushViewController(vc, animated: true)
} else {
GIDSignIn.sharedInstance().signIn()
}
}
...
func sign(_ signIn: GIDSignIn!, didSignInFor user: GIDGoogleUser!,
withError error: Error!) {
if let error = error {
print(error.localizedDescription)
return
}
guard let authentication = user.authentication else { return }
isAuthenticationComplete = authentication
}
...
}
extension SourcesViewController: SourceViewControllerDelegate {
func requestReloadTable() {
tableView.reloadData()
}
}
...
class SourceCell: UITableViewCell {
...
var sourceViewControllerDelegate: SourceViewControllerDelegate?
...
@IBAction func logInLogOutButton(_ sender: Any) {
print("Log Out button pressed")
GIDSignIn.sharedInstance().signOut()
sourceViewController?.isAuthenticationComplete = nil
sourceViewControllerDelegate?.requestReloadTable()
}
}
单击此按钮后,我仍然可以进入另一个屏幕,但是如果我重新启动应用程序,那么当我单击此按钮时,我将被带到授权页面。
解决方案
这个
var isAuthenticationComplete: GIDAuthentication?
是一个实例变量而不是保存的 1 意味着它的值对于每个新对象的创建都是 nil SourcesViewController
,您需要将您的应用程序状态保存在 bool 用户默认值中并在每次打开时检查它
节省
guard let authentication = user.authentication else { return }
isAuthenticationComplete = authentication
Userdefaults.standard.set(true,forKey:"userAuthorized")
查看
if Userdefaults.standard.bool(forKey:"userAuthorized") { }
推荐阅读
- css - 为什么相同的字体在不同的浏览器上看起来不一样?
- c# - 加载 XAML 并正确显示
- f# - 忽略函数的 F# 内联如何处理副作用函数
- tensorflow - 与 GPU 并行构建 TensorFlow 数据
- lua - Lua - 初始化空表的正确方法
- typescript - 为什么 TS Generic Type 会根据下面的代码运行两次?
- jenkins - 詹金斯。如何在几个阶段使用一个过程
- salesforce - 检测沙盒类型 (Salesforce)
- python - 如果提供了空的元素列表,如何使 IN 表达式成为可选参数?
- hybris - FlexibleSearch - 搜索产品和类别