skip to Main Content

I have implemented Sign in with Apple but the thing is that the button is always black. I would like to show it in light/ dark mode depending on the users phone.

Is there a way to achieve this?

import SwiftUI
import CryptoKit
import FirebaseAuth
import AuthenticationServices

struct SignInWithAppleButtonView: View {
    @State var currentNonce:String?
    
    var body: some View {
        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")
                        }
                        
                        print("(String(describing: Auth.auth().currentUser?.uid))")
                    default:
                        break
                        
                    }
                default:
                    break
                }
            }
        )
    }
}

2

Answers


  1. import SwiftUI
    import AuthenticationServices
    struct SignInWithAppleButtonView: View{
        var body: some View{
            
            DynamicAppleSignIn(
                onRequest: { request in
                    //Your Code
                },
                onCompletion: { result in
                    switch result {
                    case .success (let authResults):
                        print("Authorization successful.")
                    // Your Code
                    case .failure (let error):
                        print("Authorization failed: (error)")
                    // Your Code
                    }
                }
            )
        }
    }
    struct DynamicAppleSignIn : View {
        @Environment(.colorScheme) var colorScheme
        
        var onRequest: (ASAuthorizationAppleIDRequest) -> Void
        var onCompletion: ((Result<ASAuthorization, Error>) -> Void)
        
        var body: some View {
            
            switch colorScheme {
            case .dark:
                SignInWithAppleButton(
                    onRequest: onRequest,
                    onCompletion: onCompletion
                ).signInWithAppleButtonStyle(.white)
                .frame(minWidth: 140, maxWidth: 240, minHeight: 30,  maxHeight: 60, alignment: .center)
            case .light:
                SignInWithAppleButton(
                    onRequest: onRequest,
                    onCompletion: onCompletion
                ).signInWithAppleButtonStyle(.black)
                .frame(minWidth: 140, maxWidth: 240, minHeight: 30,  maxHeight: 60, alignment: .center)
            @unknown default:
                fatalError("Not Yet Implemented")
            }
            
        }
    }
    
    Login or Signup to reply.
  2. At first add

    @Environment(.colorScheme) var colorScheme

    and then add the style depends of variable

    .signInWithAppleButtonStyle(colorScheme == .dark ? .white : .black)

    In your case, it would look like this:

    import SwiftUI
    import CryptoKit
    import FirebaseAuth
    import AuthenticationServices
    
    struct SignInWithAppleButtonView: View {
        @Environment(.colorScheme) var colorScheme
        @State var currentNonce:String?
    
        var body: some View {
            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")
                            }
    
                            print("(String(describing: Auth.auth().currentUser?.uid))")
                        default:
                            break
    
                        }
                    default:
                        break
                    }
                }
            )
            .signInWithAppleButtonStyle(colorScheme == .dark ? .white : .black)
        }
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search