ios - 致命错误:无效状态:收到登录回调,但未发送登录请求
问题描述
尝试使用Swift与 Apple 登录时会发生此错误:
致命错误:无效状态:收到登录回调,但未发送登录请求
我遵循了 Firebase 的本指南。我唯一需要做的就是:
let credential = OAuthProvider.credential(withProviderID: "apple.com", idToken: idTokenString, rawNonce: nonce, accessToken: nil)
代替
let credential = OAuthProvider.credential(withProviderID: "apple.com",
IDToken: idTokenString,
rawNonce: nonce)
作为代码形式的文档给出了错误。
这是我的方法:
func authorizationController(controller: ASAuthorizationController, didCompleteWithAuthorization authorization: ASAuthorization) {
if let appleIDCredential = authorization.credential 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 {
print("Unable to fetch identity token")
return
}
guard let idTokenString = String(data: appleIDToken, encoding: .utf8) else {
print("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)
let credential = OAuthProvider.credential(withProviderID: "apple.com", idToken: idTokenString, rawNonce: nonce, accessToken: nil)
// Sign in with Firebase.
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)
return
}
// User is signed in to Firebase with Apple.
// ...
}
}
}
这是我的Git-Project。要重现错误,只需运行应用程序并点击appleButton
.
解决方案
在您的代码函数中,“startSignInWithAppleFlow”和“sha256”写在“randomNonceString”中。
修正版
private func randomNonceString(length: Int = 32) -> String {
precondition(length > 0)
let charset: Array<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
}
@available(iOS 13, *)
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.presentationContextProvider = self
authorizationController.performRequests()
}
@available(iOS 13, *)
func sha256(_ input: String) -> String {
let inputData = Data(input.utf8)
let hashedData = SHA256.hash(data: inputData)
let hashString = hashedData.compactMap {
return String(format: "%02x", $0)
}.joined()
return hashString
}
Ans 像这样从“appleButtonTapped”调用“startSignInWithAppleFlow”
@objc func appleButtonTapped(){
startSignInWithAppleFlow()
}
推荐阅读
- html - 在此页脚中居中列的问题
- javascript - 用于发布和订阅的简单 AWS IOT Web 应用程序仪表板
- c# - 尝试访问 swagger 端点时,将 Nswag 与 Odata 一起使用会产生错误
- javascript - 如何从 API 获取数据并使用 Chart.js 和 Angular 8 在其上创建图表?
- asp.net-core - 如何将消息发送到保存在 AspNetUsers 表信号 R 中的用户 ID
- python - 有没有办法动态使用星号表达式?
- r - 如何在 R 中使用带有循环的变异函数?
- java - 如何解决有关数据更改的空对象引用的此错误
- c# - 如何使用 Syncfusion PMML 从使用 sklearn MLPClassifier 训练的神经网络进行预测?
- java - 应用程序未使用 mvnDebug 在设置断点处停止