GO FURTHER, FASTER: Try the Swift Career Accelerator today! >>

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 all new Paywall Editor allow you to remotely configure your paywall view without any code changes or app updates.

Click to save your free spot now

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

Archived topic

This topic has been closed due to inactivity, so you can't reply. Please create a new topic if you need to.

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.