TEAM LICENSES: Save money and learn new skills through a Hacking with Swift+ team license >>

SOLVED Alert does not show

Forums > SwiftUI

I want to open a second view from a view in my app. However, the second view should only open if a condition is met, otherwise an alert should appear (in this case, the option to borrow the book should be opened from the detail view for a book if it is not already borrowed). The redirection also works if the book is available. If the book is not available, the button is also deactivated, but the alert is not displayed. I have added a print command to the alert call to see if it is activated - the output appears in the console, but the alert does not. What is the reason for this? Here is the button

Button("Buch ausleihen") {
    checkIfBookIsBorrowed()
}
.padding(10)
.background(Color.yellow)
.foregroundColor(.black)
.cornerRadius(8)
.sheet(isPresented: $showBorrowForm) {
  BorrowFormView(initialSearchText: book.title ?? "")
    .environmentObject(databaseManager)
}
.alert(isPresented: $showAlert) {
  Alert(
    title: Text("Buch bereits ausgeliehen"),
    message: Text("Dieses Buch wurde bereits von \(borrowerName ?? "jemandem") ausgeliehen."),
    dismissButton: .default(Text("Ok"))
   )
}

And here is the function that checks whether the book is available.

private func checkIfBookIsBorrowed() {
  if let borrower = databaseManager.borrowerOfBook(book) {
    print("Works fine.")
    borrowerName = borrower
    showAlert = true
  } else {
    showBorrowForm = true
  }
}

2      

private func checkIfBookIsBorrowed() {
  if let borrower = databaseManager.borrowerOfBook(book) {
    DispatchQueue.main.async {
      print("Works fine.")
      self.borrowerName = borrower
      self.showAlert = true
    }
  } else {
    showBorrowForm = true
  }
}

Ensure showAlert is a @State variable and it's being modified on the main thread

2      

Still no Alert shown. showAlert is initialized as

@State private var showAlert = false

and its running on main Thread

print(Thread.isMainThread)

This one shows true.

2      

Ok, I found my mistake: I had another Button with another Alert. But that alert modifier was on the VStack where both Buttons were in, so the alert did not show.

2      

Hacking with Swift is sponsored by Superwall.

SPONSORED Superwall lets you build & test paywalls without shipping updates. Run experiments, offer sales, segment users, update locked features and more at the click of button. Best part? It's FREE for up to 250 conversions / mo and the Superwall team builds out 100% custom paywalls – free of charge.

Learn More

Sponsor Hacking with Swift and reach the world's largest Swift community!

Reply to this topic…

You need to create an account or log in to reply.

All interactions here are governed by our code of conduct.

 
Unknown user

You are not logged in

Log in or create account
 

Link copied to your pasteboard.