Ios ';使用Apple'登录;对话框仅在使用内置的SignInWithAppleButton时调用
我正在尝试用我自己的定制风格实现一个使用Apple登录的Ios ';使用Apple'登录;对话框仅在使用内置的SignInWithAppleButton时调用,ios,swiftui,ios14,apple-sign-in,Ios,Swiftui,Ios14,Apple Sign In,我正在尝试用我自己的定制风格实现一个使用Apple登录的按钮。我遵循的代码与-相同,但当我使用自定义按钮时,对话框不会出现 工作的代码: SignInWithAppleButton( //Request onRequest: { request in let nonce = randomNonceString() currentNonce = nonce reques
按钮。我遵循的代码与-相同,但当我使用自定义按钮时,对话框不会出现
工作的代码:
SignInWithAppleButton(
//Request
onRequest: { request in
let nonce = randomNonceString()
currentNonce = nonce
request.requestedScopes = [.fullName, .email]
request.nonce = sha256(nonce)
},
//Completion
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
}
//Creating a request for firebase
let credential = OAuthProvider.credential(withProviderID: "apple.com",idToken: idTokenString,rawNonce: nonce)
//Sending Request to 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 as Any)
return
}
// User is signed in to Firebase with Apple.
print("SUCCESS")
}
//Prints the current userID for firebase
print("\(String(describing: Auth.auth().currentUser?.uid))")
default:
break
}
default:
break
}
}
)
不起作用的代码:
SignInWithAppleButton(
//Request
onRequest: { request in
let nonce = randomNonceString()
currentNonce = nonce
request.requestedScopes = [.fullName, .email]
request.nonce = sha256(nonce)
},
//Completion
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
}
//Creating a request for firebase
let credential = OAuthProvider.credential(withProviderID: "apple.com",idToken: idTokenString,rawNonce: nonce)
//Sending Request to 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 as Any)
return
}
// User is signed in to Firebase with Apple.
print("SUCCESS")
}
//Prints the current userID for firebase
print("\(String(describing: Auth.auth().currentUser?.uid))")
default:
break
}
default:
break
}
}
)
看法
AppleSignInButton()
.ontapsigne{
SignInWithAppleCordinator().getAppleRequest()
}
协调人
final class SignInWithAppleCoordinator: NSObject {
fileprivate var currentNonce: String?
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
}
private 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
}
func getAppleRequest(){
print("Begin request...")
let appleIDProvider = ASAuthorizationAppleIDProvider()
let nonce = randomNonceString()
currentNonce = nonce
let request = appleIDProvider.createRequest()
request.requestedScopes = [.fullName, .email]
request.nonce = sha256(nonce)
let authorizationController = ASAuthorizationController(authorizationRequests: [request])
authorizationController.delegate = self
authorizationController.performRequests()
print("Perform request...")
}
}
extension SignInWithAppleCoordinator: ASAuthorizationControllerDelegate {
func authorizationController(controller: ASAuthorizationController, didCompleteWithAuthorization authorization: ASAuthorization) {
print("Sign in to APPLE success") // THIS DOES NOT GET CALLED
}
func authorizationController(controller: ASAuthorizationController, didCompleteWithError error: Error) {
print("Sign in error APPLE ID") // THIS ALSO DOES NOT GET CALLED
}
}
使用AppleCoordinator的最终类签名:NSObject{
fileprivate变量currentNonce:字符串?
private func RandomNonCrestring(长度:Int=32)->字符串{
前提条件(长度>0)
let字符集:数组=
阵列(“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{
返回
}
如果随机String{
让inputData=数据(input.utf8)
让hashedData=SHA256.hash(数据:inputData)
让hashString=hashedData.compactMap{
返回字符串(格式:'%02x',$0)
}.加入
返回哈希字符串
}
func getAppleRequest(){
打印(“开始请求…”)
让appleIDProvider=ASAuthorizationAppleIDProvider()
设nonce=randomnocresting()
currentNonce=nonce
let request=appleIDProvider.createRequest()
request.requestedScopes=[.fullName,.email]
request.nonce=sha256(nonce)
让authorizationController=ASAuthorizationController(authorizationRequests:[请求])
authorizationController.delegate=self
authorizationController.performRequests()
打印(“执行请求…”)
}
}
带AppleCordinator的扩展名:ASAuthorizationControllerDelegate{
func authorizationController(控制器:ASAuthorizationController,已完成授权:ASAuthorization){
print(“登录到APPLE success”)//这不会被调用
}
func authorizationController(控制器:ASAuthorizationController,DidCompleteWither错误:错误){
print(“登录错误APPLE ID”)//这也不会被调用
}
}
知道问题出在哪里吗
我只是想复制内置按钮(SignInWithAppleButton
)成功登录的情况,但我需要自定义样式,因此需要对自定义样式的按钮执行操作{}