如何在我的iOS应用中检查Google身份验证状态Swift 5

问题描述

用户通过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,表示对于SourcesViewController的每个新对象创建,其值为nil,您需要将应用程序状态保存为bool用户默认值,并在每次打开时对其进行检查

保存

guard let authentication = user.authentication else { return } 
isAuthenticationComplete = authentication
Userdefaults.standard.set(true,forKey:"userAuthorized")

检查

if Userdefaults.standard.bool(forKey:"userAuthorized") { }