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 RevenueCat.

SPONSORED Take the pain out of configuring and testing your paywalls. RevenueCat's Paywalls allow you to remotely configure your entire paywall view without any code changes or app updates.

Learn more here

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.