Why Is the Alert Triggering Out of Order If Value Is Not Updated

Why is the alert triggering out of order if value is not updated?

Using a tuple variable and a method that staggers the alerts is one approach.

You need the staggering because you can't present one alert above the other reliably such as getting the wrong answer and game over at the same time.

import SwiftUI

@available(iOS 15.0, *)
struct AlertSampleView: View {
//One variable controls the single alert
@State var alertVariable:(title:String,isPresented: Bool, actionTitle: String ,action: () -> Void,message: String) = ("",false,"OK",{},"")
//MARK: Sample variables based on provided code
@State var correctAnswer = 1
@State var totalCorrectAnswers = 1
@State var attempts = 1
@State var maxAttempts = 2
var body: some View {
Button("answer", action: {
//Mimic result
flagTapped(Int.random(in: 0...2))
})
//Single alert
.alert(alertVariable.title, isPresented: $alertVariable.isPresented, actions: {
Button(alertVariable.actionTitle, action: alertVariable.action)
}, message: {
Text(alertVariable.message)
})
}
func flagTapped(_ number: Int) {
if number == correctAnswer {
scheduleAlert(title: "Correct!")

totalCorrectAnswers += 1
attempts = 0

} else {
scheduleAlert(title: "Wrong! That was the flag of ...")
attempts += 1
}
if attempts == maxAttempts {
scheduleAlert(title: "Game Over")
}
}
//Staggers the presentation of the alerts
func scheduleAlert(title: String, count:Int = 0){
//Delay Alert if there is one on the screen
if alertVariable.isPresented{
//After 5 secondsish dismiss what is there
if count >= 25{
alertVariable.isPresented = false
}
//This delay leaves a little gap between alerts
DispatchQueue.main.asyncAfter(deadline: .now() + 0.2) {
scheduleAlert(title: title, count: count + 1)
}
}else{
alertVariable.title = title
alertVariable.isPresented = true
}
}
}

@available(iOS 15.0, *)
struct AlertSampleView_Previews: PreviewProvider {
static var previews: some View {
AlertSampleView()
}
}

SwiftUI @State not triggering update when value changed by separate method

Ok, some more reading and a refactor switched to using an observable view model like this:

class ContentViewModel: ObservableObject {

var message: String? = nil {
didSet {
displayMessage = message != nil
}
}

@Published var displayMessage: Bool = false
}

struct ContentView: View {

@ObservedObject private var viewModel: ContentViewModel

var errorAlert: Alert {
Alert(title: Text("Error!"), message: Text(viewModel.message ?? "oops!"), dismissButton: .default(Text("Ok")))
}

init(viewModel: ContentViewModel) {
self.viewModel = viewModel
}

var body: some View {
VStack {
Button(action: {
self.viewModel.displayMessage.toggle()
}) {
Text("Do it!")
}
}
.alert(isPresented: $viewModel.displayMessage) { errorAlert }
}
}

Which is now working as expected. So the takeaway from this is that using observable view models is more useful even in simpler code like this.

SwiftUI Timeout Alert Warning Then Timed Out

@loremipsum's link has the answer: just wait a little between deactivating the first alert and showing the second:

struct ContentView: View {

let timer = Timer.publish(every: 1, on: .main, in: .common).autoconnect()

@State private var userActivityAlert = false
@State private var userTimeout = false
@State private var userActivity = Date.now

var body: some View {

VStack {
Text("Hello, World!")
.alert("Foo", isPresented: $userActivityAlert, actions: {
Button("I'm Here") {
userActivity = Date.now
}
}, message: { Text("Are you still there?") }
) // End show alert

Text("Hello, World!")
.alert("Foo", isPresented: $userTimeout, actions: {
Button("OK") {
// self.caRegExpired.navToHome = true
}
}, message: {
Text("Your session has expired.\nTap OK, to start over.")
}) // End Alert

}
.onReceive(timer) { time in
if userTimeout == true {
timer.upstream.connect().cancel()
} else {
caWarning()
caTimeout()
}
}
}

func caWarning() {
if Date.now >= userActivity.addingTimeInterval(5*1) {
userActivityAlert = true
}
}

func caTimeout() {
if Date.now >= userActivity.addingTimeInterval(10*1) {
userActivityAlert = false

//This delay leaves a little gap between alerts
DispatchQueue.main.asyncAfter(deadline: .now() + 0.5) {
userTimeout = true
}
}
}
}

Trouble making alerts that follow strategy.entry orders

You just need to figure out if you are already long, before going long. SO, you can use a variable for that and check its value before you trigger a buy or sell signal.

Luckily for you, I worked on the very same script when I started working with pinescript :) It's v3 but it does the trick.

//@version=3
study("Consecutive Up/Down with Alerts", overlay=true)

consecutiveBarsUp = input(3)
consecutiveBarsDown = input(3)

price = close
isLong = false
isLong := nz(isLong[1], false)

ups = 0.0
ups := price > price[1] ? nz(ups[1]) + 1 : 0

dns = 0.0
dns := price < price[1] ? nz(dns[1]) + 1 : 0

buySignal = (ups >= consecutiveBarsUp) and not nz(isLong[1])
sellSignal = (dns >= consecutiveBarsDown) and nz(isLong[1])

if (buySignal)
isLong := true

if (sellSignal)
isLong := false

alertcondition(condition=buySignal, title="BUY", message="BUY Signal.")
alertcondition(condition=sellSignal, title="SELL", message="SELL Signal.")

plotshape(buySignal, style=shape.triangleup, color=green, transp=40, text="BUY", editable=false, location=location.belowbar, size=size.small)
plotshape(sellSignal, style=shape.triangledown, color=red, transp=40, text="SELL", editable=false, location=location.abovebar, size=size.small)

Why I am not able to use multiple `.alert` dialog in my SwiftUI project?

You can create an alert type and handle it using switch statement.

enum AlertType {
case selectDelete
case selectAllDelete
}

private var alertType: AlertType?
@State private var isAlertPresented = false

...

Button(action: {
alertType = .selectDelete
isAlertPresented = true
}) {
Text("remove all")
}

...

.alert(isPresented: $isAlertPresented) {
presentAlert()
}

...

func presentAlert() -> Alert {
switch alertType {
case .selectDelete:
return Alert(title: Text("title"),
message: Text("message"),
primaryButton: .destructive(Text("Delete")) {
self.delete(item: data)
},
secondaryButton: .cancel())
case .selectAllDelete:
return Alert(title: Text("title"),
message: Text("message"),
primaryButton: .destructive(Text("Delete")) {
self.datas.removeAll()
},
secondaryButton: .cancel())
default:
return Alert(title: Text(""))
}
}

jQuery - Wait for variable to update before triggering alert

Few things here. First off, it's better to use less complex jQuery selectors, especially if your elements have id attributes. It's faster and less prone to making mistakes so I would change the code like this:

var WaardeStrafblad = "";
var WaardeVerzekering = "";

$("#Strafblad").change(function() {
if ($("#Strafblad").is(":checked")) {
WaardeStrafblad = "Ik heb geen strafblad";
} else {
WaardeStrafblad = "";
}
});

$("#Verzekering").change(function() {
if ($("#Verzekering").is(":checked")) {
WaardeVerzekering = "Ik ben bereid een verzekering af te sluiten";
} else {
WaardeVerzekering = "";
}
});

$("#Strafblad").click(function() {
alert(WaardeStrafblad + " " + WaardeVerzekering);
});

Notice how we no longer check for input:checkbox, if we already know the id there's no need to specify that it's an input of type checkbox.

The reason this fails is that the change listener fires after the click listener, so it will only print as expected if you click the Strafblad checkbox AFTER you've checked Verzekering (or if it's your second click on Strafblad).

Since the click listener will also fire on change, simply get rid of that listener and add the alert call to the end of the change listener for Strafblad like so:

var WaardeStrafblad = "";
var WaardeVerzekering = "";

$("#Strafblad").change(function() {
if ($("#Strafblad").is(":checked")) {
WaardeStrafblad = "Ik heb geen strafblad";
} else {
WaardeStrafblad = "";
}
alert(WaardeStrafblad + " " + WaardeVerzekering);
});

$("#Verzekering").change(function() {
if ($("#Verzekering").is(":checked")) {
WaardeVerzekering = "Ik ben bereid een verzekering af te sluiten";
} else {
WaardeVerzekering = "";
}
});

Perhaps it should also go at the end of the other listener but unfortunately I don't understand the language so I will just give you a minimal solution :)

Here is a working example

Getting errors using a trigger that is defined as if the stock is low than minimum level, insert the data into another table

Inside your trigger, you should:

  • explicitly list the columns of the target table you're inserting into (a generally accepted best practice for any SQL INSERT statement)
  • avoid passing NULL for the AlertDate column - by omitting that column from the INSERT statement, you'll get the DEFAULT constraint kicking in - if you pass in NULL, you get NULL stored (which is typically not what you want)
  • convert the data types when concatenating the message string (or using CONCAT, if your SQL Server version supports that).

Try this statement:

INSERT INTO alert (ProductId, ProductName, AlertType, AlertDescription)
SELECT
[ProductID], [ProductName], 'Low Stock',
CONCAT('There is only ', [InventoryOnHand], ' ', [ProductName], ' left')
FROM
inserted
WHERE
[InventoryOnHand] <= [MinimumRequired]

Trigger alert when database entries are added, not when they are removed

The solution was very simple. I changed count_cases != data.count to count_cases < data.count. That was all there was to it.

JQUERY - IF the element's current value ends with !!!, trigger an Alert

It looks like there is a \n after the !!!. Use /m flag for making the regex multiline.

if (/!!!$/m.test(value)) {
console.log("it works");
}

Check this:

var s = "When the user tl, sem.The 3 !!!";

if (/!!!$/m.test(s))
console.log("multiline matches"); //prints

if (/!!!$/.test(s))
console.log("single line matches"); //prints

s += "\n";

if (/!!!$/m.test(s))
console.log("multiline matches"); //prints

if (/!!!$/.test(s))
console.log("single line matches"); //doesn't print


Related Topics



Leave a reply



Submit