首页 > 解决方案 > 如何在我的 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()
    }
}

单击此按钮后,我仍然可以进入另一个屏幕,但是如果我重新启动应用程序,那么当我单击此按钮时,我将被带到授权页面。

标签: iosswiftgoogle-drive-api

解决方案


这个

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") { }

推荐阅读