我很好奇如何在启动我的应用程序时检查用户身份验证。在我的应用程序委托中,我正在执行以下操作。该loggedIn
变量将根据用户当前是否使用“Sign In With Apple”按钮进行设置
extension UIApplication {
func switchHostingController() {
var loggedIn = false
let provider = ASAuthorizationAppleIDProvider()
let userID = UserDefaults.standard.object(forKey: "userID") as? String
provider.getCredentialState(forUserID: userID!) { state, error in
switch state {
case .authorized:
// Credentials are valid.
loggedIn = true
break
case .revoked:
// Credential revoked, log them out
loggedIn = false
break
case .notFound:
// Credentials not found, show login UI
loggedIn = false
break
case .transferred:
loggedIn = false
@unknown default:
loggedIn = false
}
}
if (loggedIn == false)
{
let window = UIApplication.shared.windows.filter {$0.isKeyWindow}.first
window?.rootViewController = UIHostingController(rootView: ContentView())
} else {
let main = Main()
let window = UIApplication.shared.windows.filter {$0.isKeyWindow}.first
window?.rootViewController = UIHostingController(rootView: main)
}
}
}
由于某种原因,上面的loggedIn
var 总是返回 false。我知道这与forUserID: userID!
不返回任何东西有关。但它适用于其他观点......