UIApplication.shared.windows.first?.rootViewController?.present(alert, animated: true) Deprecated

666 Views Asked by At

I am trying to present an alert for password reset link sent through Firebase with this code inside a func, but it says deprecated and my alert is not showing. Any help to solve?

Thanks!

func resetPassword() {
    let alert = UIAlertController(title: "Reset Password", message: "Inserisci la tua e-mail per resettare la password", preferredStyle: .alert)
    
    alert.addTextField { (password) in
        password.placeholder = "Email"
        }
    
    let proceed = UIAlertAction(title: "Reset", style: .default) { (_) in
        
        // Sending email Link
        
        if alert.textFields![0].text! != "" {
            
            withAnimation {
                self.isLoading.toggle()
            }
            
            Auth.auth().sendPasswordReset(withEmail: alert.textFields![0].text!) { (err) in
              
                withAnimation {
                    self.isLoading.toggle()
                }
                
                if err != nil {
                    print(err?.localizedDescription as Any)
                    self.alertMsg = err!.localizedDescription
                    self.alert.toggle()
                    return
                }
                // Conferma invio link
                self.alertMsg = "Il link per il reset della password è stato correttamente inviato"
                print(self.alertMsg)
                self.alert.toggle()
            }
        }
    }
    let cancel = UIAlertAction(title: "Annulla", style: .destructive, handler: nil)
    
    alert.addAction(cancel)
    alert.addAction(proceed)
    
    ***UIApplication.shared.windows.first?.rootViewController?.present(alert, animated: true)***
    

}
1

There are 1 best solutions below

0
Umair Khan On

Preview Image

SwiftUI provided us standard way to show alert like this, you can use this approach to achieve what you're looking for

import SwiftUI

struct AlertView: View {
    // MARK: - PROPERTIES
    
    @State private var showAlert: Bool = false
    
    // MARK: - BODY
    
    var body: some View {
        VStack(spacing: 40){
            Text("Hello World")
                .font(.largeTitle)
                .fontWeight(.bold)
            
            Button("Show Alert") {
                showAlert = true
            }
            .alert("Title", isPresented: $showAlert, actions: {
                Button("Cancel", role: .cancel) {}
                
                Button("Delete", role: .destructive) {}
            })//: ALERT
            .padding(.horizontal, 30)
            .padding(.vertical, 15)
            .background(.blue)
            .foregroundColor(.white)
        }//: VSTACK
    }
}

// MARK: - PREVIEW

struct AlertView_Previews: PreviewProvider {
    static var previews: some View {
        AlertView()
    }
}