swiftui - 带有条件绑定(bind)的 SwiftUI 中的错误必须具有可选类型,而不是字符

我正在使用 Sign In With Apple 制作应用程序,当我输入代码的“完成时”部分时,它无法正常工作。我试着放一个可选的“?”在错误的部分后面,但它不起作用。环顾四周,我看到了类似的答案,但没有任何帮助。提前致谢:)

import SwiftUI
import CryptoKit
import AuthenticationServices
import FirebaseAuth


struct LoginView: View {
    
    @EnvironmentObject var userAuth: UserAuth
    @State var currentNonce: String
    
    
    // Adapted from https://auth0.com/docs/api-auth/tutorials/nonce#generate-a-cryptographically-random-nonce
    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 {
                    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
    }
    
    
    var body: some View {
        ZStack {
            Color.yellow
                .ignoresSafeArea()
            
            SignInWithAppleButton(
                onRequest: { request in
                    let nonce = randomNonceString()
                    currentNonce = nonce
                    request.requestedScopes = [.fullName, .email]
                    request.nonce = sha256(nonce)
                },
                onCompletion: { result in
                    switch result {
                    case .success(let authResults):
                        switch authResults.credential {
                        case let appleIDCredential as ASAuthorizationAppleIDCredential:
                            
                            guard let nonce = currentNonce else {
                                fatalError("Invalid state: A login callback was received, but no login request was sent.")
                            }
                            guard let appleIDToken = appleIDCredential.identityToken else {
                                fatalError("Invalid state: A login callback was received, but no login request was sent.")
                            }
                            guard let idTokenString = String(data: appleIDToken, encoding: .utf8) else {
                                print("Unable to serialize token string from data: \(appleIDToken.debugDescription)")
                                return
                            }
                            
                            let credential = OAuthProvider.credential(withProviderID: "apple.com",idToken: idTokenString,rawNonce: nonce)
                            Auth.auth().signIn(with: credential) { (authResult, error) in
                                if (error != nil) {
                                    // Error. If error.code == .MissingOrInvalidNonce, make sure
                                    // you're sending the SHA256-hashed nonce as a hex string with
                                    // your request to Apple.
                                    print(error?.localizedDescription as Any)
                                    return
                                }
                                print("signed in")
                                self.userAuth.login()
                            }
                            
                            print("\(String(describing: Auth.auth().currentUser?.uid))")
                        default:
                            break
                            
                        }
                    default:
                        break
                    }
                }
            )
            .frame(width: 200, height: 45, alignment: .center)
            .padding(.init(top: 400, leading: 50, bottom: 20, trailing: 200))
        }
    }
}

最佳答案

声明为可选

struct LoginView: View {

    @EnvironmentObject var userAuth: UserAuth
    @State var currentNonce: String?            // << here !!

关于swiftui - 带有条件绑定(bind)的 SwiftUI 中的错误必须具有可选类型,而不是字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/72905771/

相关文章:

databricks - Databricks 中的目录

ios - SwiftUI:有条件地隐藏 View 而不重新创建它

typescript - 将通用 typescript 类型限制为单个字符串文字值,不允许联合

java - 是否可以向 OpenAPI 添加方法?

r - 在 R 中使用 dplyr 包 Lag 函数时有没有办法省略 NA?

r - 按两个数字对列名称进行排序

javascript - 使用 Object.keys() 获取 searchParams

xaml - 删除开关中的文本

c - 尝试创建一个 C 程序来打印出所有具有有理平方根的数字?

haskell - 在 Haskell 中内存递归函数