Alerts are an important part of any website. They provide users with important information, such as success messages, error messages, warnings, and confirmation dialogs. However, the traditional JavaScript alerts are not very attractive and can be annoying for users. That's where SweetAlert2 comes in.
SweetAlert2 is a library that allows you to create beautiful and customizable pop-up dialogs. In this article, we'll explore the benefits of SweetAlert2 and how to use it in your SwifWeb application.
If you are new to SwifWeb please take a look how to create new project in this article.
In the project open Package.swift
and edit the dependencies
section to make it look like this:
dependencies: [
// the rest of the other dependencies including swifweb/web
.package(
url: "https://github.com/swifweb/sweetalert2",
from: "1.0.0"
),
]
Next edit executableTarget
to make it look like this:
.executableTarget(name: "App", dependencies: [
.product(name: "Web", package: "web"),
.product(name: "SweetAlert", package: "sweetalert2")
]),
Then open App.swift
add import SweetAlert
and configure it in didFinishLaunching
method like this:
Lifecycle.didFinishLaunching {
SweetAlert.configure() // it will use default theme
}
It will not work if you forget to configure it.
Choose one of the following
SweetAlert.configure(.dark)
SweetAlert.configure(.minimal)
SweetAlert.configure(.borderless)
SweetAlert.configure(.bootstrap4)
SweetAlert.configure(.boolma)
SweetAlert.configure(.materialUI)
SweetAlert.configure(.wordpressAdmin)
The full list with pictures is on the official site
Declare your own theme in an extension:
extension SweetAlertTheme {
static var myCustom: Self { "my-custom" }
}
Add my-custom.css
into Sources/App/css
folder and edit resources
in Package.swift
as following:
.executableTarget(name: "App", dependencies: [
.product(name: "Web", package: "web"),
.product(name: "SweetAlert", package: "sweetalert2")
], resources: [
.copy("css/my-custom.css"),
.copy("css")
]),
Then use it simply this way:
SweetAlert.configure(.myCustom)
SweetAlert2 is easy to implement and use, with a simple and intuitive API. You can create alerts with just a few lines of code. SweetAlert2 also supports promises, which allows you to chain multiple alerts together or execute code after an alert is dismissed.
The syntax is similar to JS but is crafted beautifully in Swift and also includes the conveniences of SwiftWeb!
Swal.fire("Any fool can use a computer")
Swal.fire(
"The Internet?",
"That thing is still around?",
.question
)
One of the main benefits of SweetAlert2 is the ability to customize the look and feel of your alerts. You can customize the background color, font color, and border color of your alerts using convenient methods or CSS. This allows you to create alerts that fit seamlessly into your web app design.
Swal.html {
H1("Title")
H4("Message")
Div {
Button("OK").onClick {
Swal.clickConfirm()
}
Button("Cancel").onClick {
Swal.clickCancel()
}
}
}
.fire()
Swal.icon(.error)
.title("Oops...")
.text("Something went wrong!")
.footer {
A("Why do I have this issue?").href("#why")
}
.fire()
Swal.imageUrl("https://placeholder.pics/svg/300x1500")
.imageHeight(1500)
.imageAlt("A tall image")
Swal.showDenyButton()
.showCancelButton()
.confirmButtonText("Save")
.denyButtonText("Don't save")
.fire { result in
if result.isConfirmed {
Swal.icon(.success)
.titleText("Saved!")
.fire()
} else if result.isDenied {
Swal.icon(.info)
.titleText("Changes are not saved")
.fire()
}
}
Swal.position(.topEnd)
.icon(.success)
.title("Your work has been saved")
.showConfirmButton(false)
.timer(1.5) // seconds
.fire()
SweetAlert2 provides a more elegant and user-friendly experience for displaying alerts compared to the traditional JavaScript alerts. SweetAlert2 alerts are visually appealing and less obtrusive, making them less annoying for users. You can also add animations and sound effects to your alerts to make them more engaging.
Swal.title("Custom animation with Animate.css")
.showClass(animatePopup: .fadeInDown)
.hideClass(animatePopup: .fadeOutUp)
.fire()
Beautiful icons
SweetAlert2 supports multiple types of alerts, including success messages, error messages, warnings, and confirmation dialogs.
Swal.icon(.success)
Swal.icon(.error)
Swal.icon(.warning)
Swal.icon(.info)
Swal.icon(.question)
SweetAlert2 is responsive and works well on both desktop and mobile devices. The library is built with accessibility in mind and is compliant with web accessibility standards, making it usable by people with disabilities. This ensures that your alerts are accessible to all users, regardless of their device or ability.
Swal
.title {
Strong {
"HTML "
U("example")
}
}
.icon(.info)
.html {
"You can use"
B("bold text, ")
A("links").href("https://swifweb.com")
"and other HTML tags"
}
.showCloseButton()
.showCancelButton()
.focusConfirm(false)
.confirmButtonText("Great!")
.confirmButtonAriaLabel("great")
.cancelButtonText("Cancel :(")
.cancelButtonAriaLabel("cancel")
.fire()
SweetAlert2 offers a wide range of features, including the ability to add images, icons, input fields, and even timers to your alerts.
A message with auto close timer
@State var timerLabel = ""
Swal
.titleText("Auto close alert!")
.html {
B(self.$timerLabel.map { "\($0)" })
}
.timer(2.0) // in seconds
.timerProgressBar()
.didOpen {
Dispatch.interval(0.1) { task in
if Swal.isTimerRunning() {
self.timerLabel = "\(Swal.getTimerLeft())"
} else {
task.invalidate()
}
}
}
.fire { result in
if result.dismiss == .timer {
print("I was closed by the timer")
}
}
More examples available in the readme on github.
One of the most powerful features of SweetAlert2 is its ability to be controlled programmatically. You can create your own dynamic alerts that respond to any custom elements and events.
General methods
Swal.isVisible() // Determine if popup is shown
Swal.close() // Closes the currently open SweetAlert2 popup
Buttons
Swal.enableButtons() // Enable "Confirm" and "Cancel" buttons
Swal.disableButtons() // Disable "Confirm" and "Cancel" buttons
Swal.clickConfirm() // Click the "Confirm"-button
Swal.clickDeny() // Click the "Deny"-button
Swal.clickCancel() // Click the "Cancel"-button
Loader
Swal.isLoading() // Determine if popup is in the loading state
Swal.showLoading() // Shows loader (spinner)
Swal.hideLoading() // Hides loader and shows back the button
Timer
Swal.isTimerRunning() // Returns the status of a timer
Swal.stopTimer() // Stops the timer
Swal.resumeTimer() // Resume the timer previously stopped
Swal.toggleTimer() // Toggle state between stopped and running
Swal.getTimerLeft() // Returns the time left
Swal.increaseTimer(n) // Increase the timer by n seconds
Inputs
Swal.disableInput() // Disable input
Swal.enableInput() // Enable input
Validation
Swal.showValidationMessage(message) // Show the validation message
Swal.resetValidationMessage() // Hide the validation message
Swal.getValidationMessage() // Get the validation message
Parameters
// Determine if parameter name is valid
Swal.isValidParameter(param)
// Determine if parameter name is valid for Swal.update() method
Swal.isUpdatableParameter(param)
SweetAlert2 is a popular choice for developers who want to create attractive and user-friendly alerts for their web applications. The library provides a range of benefits, so if you're looking for a SwifWeb alert library that can help you improve the user experience of your web applications, SweetAlert2 is definitely worth checking out.
Wanna learn more? Stay tuned for the upcoming articles!
Don’t hesitate to ask any questions