I am trying to implement notifications in my SwiftUI app, but have not managed to do so after extensive research on Google and other search engines.
-
3SwiftUI has nothing to do with notifications don’t limit your search to SwiftUI results. There are websites were you can hire mentors or freelancers to provide 1:1 help. We don’t have enough information to help you troubleshoot.lorem ipsum– lorem ipsum2022-11-25 02:22:59 +00:00Commented Nov 25, 2022 at 2:22
-
Does this answer your question? How to set up push notifications in SwiftNicolapps– Nicolapps2022-11-25 03:51:51 +00:00Commented Nov 25, 2022 at 3:51
-
Can you give an example of the type of notification that you’re looking to create?jnpdx– jnpdx2022-11-25 03:53:54 +00:00Commented Nov 25, 2022 at 3:53
Add a comment
|
1 Answer
Here's a simple example on how to use notifications in a SwiftUI app. It requests for permissions and checks if they are granted, and allows you to send a notification if so.
Do note that notifications from apps won't appear if the app they originate from is in the foreground, so I demonstrate closing the app quickly before the notification is sent to view it.
Here's the whole example code the demo uses:
import SwiftUI
import UserNotifications
struct ContentView: View {
@State private var permissionGranted = false
private func requestPermissions() {
UNUserNotificationCenter.current().requestAuthorization(options: [.alert, .badge, .sound]) { success, error in
if success {
permissionGranted = true
} else if let error = error {
print(error.localizedDescription)
}
}
}
private func sendNotification() {
let notificationContent = UNMutableNotificationContent()
notificationContent.title = "Hello world!"
notificationContent.subtitle = "Here's how you send a notification in SwiftUI"
let trigger = UNTimeIntervalNotificationTrigger(timeInterval: 5, repeats: false)
// you could also use...
// UNCalendarNotificationTrigger(dateMatching: .init(year: 2022, month: 12, day: 10, hour: 0, minute: 0), repeats: true)
let req = UNNotificationRequest(identifier: UUID().uuidString, content: notificationContent, trigger: trigger)
UNUserNotificationCenter.current().add(req)
}
var body: some View {
VStack {
if !permissionGranted {
Button("Request Permission") {
requestPermissions()
}
}
if permissionGranted {
Button("Send Notification") {
sendNotification()
}
}
}
.onAppear {
// Check if we already have permissions to send notifications
UNUserNotificationCenter.current().getNotificationSettings { settings in
if settings.authorizationStatus == .authorized {
permissionGranted = true
}
}
}
.padding()
}
}
1 Comment
Duck
video link is broken