首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >防火墙,苹果注册,SwiftUI - ASAuthorizationControllerDelegate成功功能未调用

防火墙,苹果注册,SwiftUI - ASAuthorizationControllerDelegate成功功能未调用
EN

Stack Overflow用户
提问于 2022-01-27 22:47:36
回答 1查看 157关注 0票数 0

我已经实现了自己的AppleSignUpButton。它调用这段代码来完成实际的苹果sigThe旋转器。

当我按下cancel时,将按预期调用此函数:

代码语言:javascript
运行
复制
func authorizationController(controller _: ASAuthorizationController, didCompleteWithError error: Error) {..}

所以我唯一的问题是这个:

代码语言:javascript
运行
复制
func authorizationController(controller _: ASAuthorizationController, didCompleteWithAuthorization authorization: ASAuthorization) {..}

这是我的课,处理苹果注册:

代码语言:javascript
运行
复制
import AuthenticationServices
import CryptoKit
import Firebase
import FirebaseAuth
import Foundation

@objc class AppleAuthProvider: NSObject, AuthProvider {
    
    @Published var loggedInUser: FIRUser?
    
    var completion: ((Result<User, Error>) -> Void)?

    private var currentNonce: String?

    func signIn(completion: @escaping (Result<User, Error>) -> Void) {
        self.completion = completion

        startSignInWithAppleFlow()
    }

    func signOut(completion _: @escaping (Result<Void, Error>) -> Void) {
        ()
    }

    func startSignInWithAppleFlow() {
        let nonce = randomNonceString()
        currentNonce = nonce
        let appleIDProvider = ASAuthorizationAppleIDProvider()
        let request = appleIDProvider.createRequest()
        request.requestedScopes = [.fullName, .email]
        request.nonce = sha256(nonce)

        let authorizationController = ASAuthorizationController(authorizationRequests: [request])
        authorizationController.delegate = self
        authorizationController.performRequests()
    }

    private func randomNonceString(length: Int = 32) -> String {
        precondition(length > 0)
        let charset: [Character] =
            Array("0123456789ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvwxyz-._")
        var result = ""
        var remainingLength = length

        while remainingLength > 0 {
            let randoms: [UInt8] = (0 ..< 16).map { _ in
                var random: UInt8 = 0
                let errorCode = SecRandomCopyBytes(kSecRandomDefault, 1, &random)
                if errorCode != errSecSuccess {
                    completion?(.failure(fatalError(
                        "Unable to generate nonce. SecRandomCopyBytes failed with OSStatus \(errorCode)"
                    )))
                }
                return random
            }

            randoms.forEach { random in
                if remainingLength == 0 {
                    return
                }

                if random < charset.count {
                    result.append(charset[Int(random)])
                    remainingLength -= 1
                }
            }
        }

        return result
    }

    private func sha256(_ input: String) -> String {
        let inputData = Data(input.utf8)
        let hashedData = SHA256.hash(data: inputData)
        let hashString = hashedData.compactMap {
            String(format: "%02x", $0)
        }.joined()

        return hashString
    }
}

extension AppleAuthProvider: ASAuthorizationControllerDelegate {
    func authorizationController(controller _: ASAuthorizationController, didCompleteWithAuthorization authorization: ASAuthorization) {
        if let appleIDCredential = authorization.credential as? ASAuthorizationAppleIDCredential {
            guard let nonce = currentNonce else {
                completion?(.failure(fatalError(
                    "Invalid state: A login callback was received, but no login request was sent."
                )))
                return
            }
            guard let appleIDToken = appleIDCredential.identityToken else {
                completion?(.failure(fatalError(
                    "Unable to fetch identity token"
                )))

                return
            }
            guard let idTokenString = String(data: appleIDToken, encoding: .utf8) else {
                completion?(.failure(fatalError(
                    "Unable to serialize token string from data: \(appleIDToken.debugDescription)"
                )))
                return
            }
            // Initialize a Firebase credential.
            let credential = OAuthProvider.credential(withProviderID: "apple.com",
                                                      idToken: idTokenString,
                                                      rawNonce: nonce)
            // Sign in with Firebase.
            Auth.auth().signIn(with: credential) { [weak self] _, error in
                if let error = error {
                    self?.completion?(.failure(error))
                } 
               // User is signed in to Firebase with Apple.
               // ...
            }
        }
    }

    func authorizationController(controller _: ASAuthorizationController, didCompleteWithError error: Error) {
        completion?(.failure(fatalError(
            "Sign in with Apple errored: \(error)"
        )))
    }
}
EN

回答 1

Stack Overflow用户

发布于 2022-01-28 22:06:30

它在模拟器上没有工作,但在真正的设备上工作正常。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/70886772

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档