1

我很好奇如何在启动我的应用程序时检查用户身份验证。在我的应用程序委托中,我正在执行以下操作。该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)
        }
    }
}

由于某种原因,上面的loggedInvar 总是返回 false。我知道这与forUserID: userID!不返回任何东西有关。但它适用于其他观点......

4

1 回答 1

1

通过制作一个检查是否进行身份验证的功能来解决它​​。如果是这样,请将 bool 设置为 true。然后检查 bool 以显示正确的视图。还必须创建一个调度组,以便提供者方法可以在返回值之前完成。

struct MeusicApp: App {
    func checkit() -> Bool {
        let group = DispatchGroup()
            group.enter()
        let userID = UserDefaults.standard.object(forKey: "userID") as? String
        let provider = ASAuthorizationAppleIDProvider()
        var stateBool = false
        provider.getCredentialState(forUserID: userID ?? "") { [self] state, error in
          switch state {
          case .authorized:
            // Credentials are valid.
            stateBool = true
            group.leave()
            break
          case .revoked:
            // Credential revoked, log them out
            stateBool = false
            group.leave()
            break
          case .notFound:
            // Credentials not found, show login UI
            stateBool = false
            group.leave()
            break
          case .transferred:
            print("Transferred")
          @unknown default:
            stateBool = false
            group.leave()
          }
        }
        group.wait()
        return stateBool
    }
    var body: some Scene {
        WindowGroup {
            if checkit() {
                Main()
            } else {
                ContentView()
            }
        }
    }
}
于 2020-11-25T02:56:11.693 回答