Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/sql-server-2005/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ios 更换';IDToken';与';idToken';使用Firebase与Apple快速登录_Ios_Swift_Firebase - Fatal编程技术网

Ios 更换';IDToken';与';idToken';使用Firebase与Apple快速登录

Ios 更换';IDToken';与';idToken';使用Firebase与Apple快速登录,ios,swift,firebase,Ios,Swift,Firebase,我正在尝试使用Firebase与Apple登录。Firebase文档说要使用let credential=OAuthProvider.credential(withProviderID:“apple.com”,IDToken:idTokenString,rawnice:nonce),但是Xcode给出了错误并建议修复 如果我遵循Xcode的建议,应用程序将崩溃,状态为无效:收到登录回调,但未发送登录请求。。我已经看到了关于堆栈溢出的所有其他问题,但没有一个解决了这个问题。这是Firebase

我正在尝试使用Firebase与Apple登录。Firebase文档说要使用
let credential=OAuthProvider.credential(withProviderID:“apple.com”,IDToken:idTokenString,rawnice:nonce)
,但是Xcode给出了错误并建议修复


如果我遵循Xcode的建议,应用程序将崩溃,状态为
无效:收到登录回调,但未发送登录请求。
。我已经看到了关于堆栈溢出的所有其他问题,但没有一个解决了这个问题。这是Firebase SDK当前版本的问题还是我的错误。

试试我的代码,它适合我

import CryptoKit
import Firebase
import AuthenticationServices

extension SocietyLoginViewController {

    @available(iOS 13, *)
    func appleLogin() {
        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
    }

    // Adapted from https://auth0.com/docs/api-auth/tutorials/nonce#generate-a-cryptographically-random-nonce
    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.0, *)
extension SocietyLoginViewController: ASAuthorizationControllerDelegate , ASAuthorizationControllerPresentationContextProviding {

    func presentationAnchor(for controller: ASAuthorizationController) -> ASPresentationAnchor {
        return self.view.window!
    }

    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 {
                return
            }
            guard let idTokenString = String(data: appleIDToken, encoding: .utf8) else {
                return
            }
            // Initialize a Firebase credential.
            let credential = OAuthProvider.credential(withProviderID: "apple.com", idToken: idTokenString, rawNonce: nonce)
            // Sign in with Firebase.

        }
    }

    func authorizationController(controller: ASAuthorizationController, didCompleteWithError error: Error) {
        // Handle error.
        print("Sign in with Apple errored: \(error)")
   }
}


导入加密工具包
进口火基
导入身份验证服务
扩展SocietyLoginViewController{
@可用(iOS 13,*)
func appleLogin(){
设nonce=randomnocresting()
CurrentNoce=非货币
让appleIDProvider=ASAuthorizationAppleIDProvider()
let request=appleIDProvider.createRequest()
request.requestedScopes=[.fullName,.email]
request.nonce=sha256(nonce)
让authorizationController=ASAuthorizationController(authorizationRequests:[请求])
authorizationController.delegate=self
authorizationController.presentationContextProvider=self
authorizationController.performRequests()
}
@可用(iOS 13,*)
func sha256(输入:字符串)->字符串{
让inputData=数据(input.utf8)
让hashedData=SHA256.hash(数据:inputData)
让hashString=hashedData.compactMap{
返回字符串(格式:'%02x',$0)
}.加入
返回哈希字符串
}
//改编自https://auth0.com/docs/api-auth/tutorials/nonce#generate-a-加密-随机-nonce
func random无限制(长度:Int=32)->字符串{
前提条件(长度>0)
let字符集:Array=Array(“0123456789abcdefghijklmnopqrstuvxyzabcdefghijklmnopqrstuvxyz-。)
var result=“”
var remainingLength=长度
当剩余长度大于0时{
让randoms:[UInt8]=(0..<16).map{uu}in
随机变量:UInt8=0
让errorCode=SecRandomCopyBytes(kSecRandomDefault、1和random)
如果errorCode!=errSecSuccess{
fatalError(“无法生成nonce.SecRandomCopyBytes,OSStatus\(错误代码)”失败)
}
返回随机数
}
randoms.forEach{random in
如果剩余长度==0{
回来
}
如果随机ASPresentationAnchor{
返回self.view.window!
}
func authorizationController(控制器:ASAuthorizationController,已完成授权:ASAuthorization){
如果让appleIDCredential=authorization.credential as?ASAuthorizationAppleIDCredential{
保护let nonce=当前nonce else{
fatalError(“无效状态:收到登录回调,但未发送登录请求。”)
}
guard let appleIDToken=appleIDCredential.identityToken else{
回来
}
guard let idTokenString=String(数据:appleIDToken,编码:.utf8)else{
回来
}
//初始化Firebase凭据。
让credential=OAuthProvider.credential(withProviderID:“apple.com”,idToken:idTokenString,rawnice:nonce)
//使用Firebase登录。
}
}
func authorizationController(控制器:ASAuthorizationController,DidCompleteWither错误:错误){
//处理错误。
打印(“使用Apple登录时出错:\(错误)”)
}
}