SignInWithAppleButton not working when embedded in View?

64 views Asked by At

I am currently implementing sign in with AppleID for my app which then redirects to mongoDB atlas.

I have a working implementation of the SignInWithAppleButton. However the code only works when running 'on its own'

i have a LoginView that i want to enhance with the SignInWithApple Button function

    
    @Environment(\.colorScheme) var colorScheme
    
    enum Field: Hashable {
        case username
        case password
    }
    
    @Binding var username: String?
    @Binding var userEmail: String?
    @Binding var firstLogin: Bool?
    @Binding var prename: String
    @Binding var surname: String
    @State var email: String = ""
    
    @State var wds: WatchlistDataService?
    @StateObject var vm: LoginViewModel = LoginViewModel()
    
    @State private var resetEmail = ""
    @State private var password = ""
    @State private var errorMessage = ""
    @State private var inProgress = false
    @State var showDialog = false
    @State var showPWReset = false
    @State var showPWResetConfirmation = false
    
    @State var showOverlay = true
    
    @FocusState private var focussedField: Field?
    
    var body: some View {
        NavigationView {
            ZStack {
                LinearGradient(gradient: Gradient(colors: [Color.theme.backGroundGreen, Color.theme.backGroundPurple]), startPoint: .topTrailing, endPoint: .bottomLeading)
                    .ignoresSafeArea()
                VStack(spacing: 16) {
                    Image("Logo")
                        .resizable()
                        .frame(width: 300, height: 61)
                        .padding(.top, 75)
                        .padding(.bottom, 40)
                    Text(errorMessage)
                        .foregroundColor(.red)
                        .padding(.horizontal)
                    TextField("E-Mail Adresse", text: $email)
                        .padding(10)
                        .overlay {
                            RoundedRectangle(cornerRadius: 5)
                                .stroke(Color.theme.accent.opacity(0.1), lineWidth: 2)
                        }
                        .padding(.horizontal, 10)
                        .focused($focussedField, equals: .username)
                        .submitLabel(.next)
                        .onSubmit { focussedField = .password }
                    
                    SecureField("Passwort", text: $password)
                        .padding(10)
                        .overlay {
                            RoundedRectangle(cornerRadius: 5)
                                .stroke(Color.theme.accent.opacity(0.1), lineWidth: 2)
                        }
                        .padding(.horizontal, 10)
                        .focused($focussedField, equals: .password)
                        .onSubmit{userAction()
                            endTextEditing()}
                        .submitLabel(.go)
                    HStack {
                        loginButton
                            .disabled(email == "" || password == "")
                        NavigationLink {
                            RegistrationView(prename: $prename, surname: $surname, email: $email)
                        } label: {
                            registerButton
                        }
                    }
                                          
                    signInWithApple
                    
                    HStack{
                        Spacer()
                        NavigationLink {
                            PasswordResetView()
                        } label: {
                            Text("Ich habe mein Passwort vergessen")
                                .font(.caption)
                                .underline()
                                .foregroundColor(colorScheme == .light ? .blue : Color.theme.accent)
                        }
                        .padding()
                        .ignoresSafeArea(.keyboard, edges: .bottom)
                        Spacer()
                    }
                    if inProgress {
                        ProgressView()
                    }
                }
                .onTapGesture {
                self.endTextEditing()
            }
                .onAppear {
                    DispatchQueue.main.asyncAfter(deadline: .now() + 0.5) {
                        focussedField = .username
                    }
                    Analytics.logEvent(AnalyticsEventScreenView,
                                       parameters: [AnalyticsParameterScreenName: "Login"])
                }
                .confirmationDialog("Bitte gültige Email Adresse eingeben.", isPresented: $showDialog, titleVisibility: .visible, actions: {
                    Button("Ok") {
                        showDialog = false
                    }
                })
            }

        }
        .navigationBarTitle("")
                .navigationBarBackButtonHidden(true)
                .navigationBarHidden(true)
    }
    
}

extension LoginView {
    var loginButton: some View {
        Button {
            userAction()
        } label: {
            ZStack{
                RoundedRectangle(cornerRadius: 10)
                    .stroke(lineWidth: 1)
                    .foregroundColor(Color.theme.accent)
                RoundedRectangle(cornerRadius: 10)
                    .foregroundColor(Color.theme.accent.opacity(0.2))
                Text("Mit E-Mail anmelden")
                    .foregroundStyle(Color.theme.primaryFont)
            }
            .frame(width: 180, height: 40)
        }
    }
    
    var registerButton: some View {
            ZStack{
                RoundedRectangle(cornerRadius: 10)
                    .stroke(lineWidth: 1)
                    .foregroundColor(Color.theme.accent)
                RoundedRectangle(cornerRadius: 10)
                    .foregroundColor(Color.theme.accent.opacity(0.2))
                Text("Mit E-Mail registrieren")
                    .foregroundStyle(Color.theme.primaryFont)
            }
            .frame(width: 180, height: 40)
    }
    
    func loginWithApple(idToken: String){
        print("loginWithApple()")
        // Fetch IDToken via the Apple SDK
        let credentials = Credentials.apple(idToken: idToken)
        myRealmApp.login(credentials: credentials) { (result) in
            switch result {
            case .failure(let error):
                print("Login failed: \(error.localizedDescription)")
            case .success(let user):
                vm.updateLoginStatetoLoggedIn()
                print("Successfully logged in as user \(user)")
                // Now logged in, do something with user
                // Remember to dispatch to main if you are doing anything on the UI thread
            }
        }
    }
    
    var signInWithApple: some View {
        SignInWithAppleButton(.signIn) { request in
            print("request started...")
            request.requestedScopes = [.email, .fullName]
        } onCompletion: { result in
            print("request completed...")
            print ("result: \(result)")
            switch result {
            case .success(let authResults):
                print("Authorisation successful")
                switch authResults.credential {
                case let credential as ASAuthorizationAppleIDCredential:
                    if let idToken = credential.identityToken {
                        guard let idTokenString = String(data: idToken, encoding: .utf8) else {
                            print("Unable to serialize token string from data: \(idToken.debugDescription)")
                            return
                        }
                        loginWithApple(idToken: idTokenString)
                        self.username = credential.email
                        self.prename = credential.fullName?.givenName ?? ""
                        self.surname = credential.fullName?.familyName ?? ""
                        self.email = credential.email ?? ""
                    }
                default:
                    print("default")
                    break
                }
            case .failure(let error):
                print("Authorisation failed: \(error.localizedDescription)")
            }
        }
        .frame(height: 50)
        .padding()
    }

}

if i put the code directly in my ContentView (just the var with the Button and the function, without anything else) its working as supposed. Currently, the PopUp sheet does not arise if the button is clicked.

1

There are 1 answers

0
Marvin Meinhard On

Found the Problem. the .onTapGesture() on the VStack overayed the funtion of the button