How to use Local Notifications in SwiftUI

Share on facebook
Share on twitter
Share on pinterest

Today we’ll show you a quick way to use local notifications in SwiftUI apps. There a just a few steps you need to follow. In our demo app, we’re creating a simple notification that gets triggered after a specified time interval. Let’s go!

This is how our notification should look like in the end:


Step 1: In your SwiftUI app, create a new class called LocalNotificationManager that adopts the @ObservableObject. Adopting this protocol isn’t a must but can be useful if you want your SwiftUI view to react when a local notifications gets fired.

import Foundation
import SwiftUI

class LocalNotificationManager: ObservableObject {
    

}


Step 2: Inside this class declare an array that holds the Notification objects that get created.

class LocalNotificationManager: ObservableObject {
    
    var notifications = [Notification]()
    
}


Step 3: Before firing notification, we need to ask the user for his permission. We want to do this when initialising the LocalNotificationManager instance.

init() {
        UNUserNotificationCenter.current().requestAuthorization(options: [.alert, .badge, .sound]) { granted, error in
            if granted == true && error == nil {
                print("Notifications permitted")
            } else {
                print("Notifications not permitted")
            }
        }
    }


Step 4: Inside our LocalNotificationManager class, we create a function that uses certain parameters to create a Notification instance. 

func sendNotification(title: String, subtitle: String?, body: String, launchIn: Double) {
        //...
    }


Step 5: Inside the function, we define which content we want to use for the Notification. We can even attach media like images to it.
 

func sendNotification(title: String, subtitle: String?, body: String, launchIn: Double) {
        
        let content = UNMutableNotificationContent()
        content.title = title
        if let subtitle = subtitle {
            content.subtitle = subtitle
        }
        content.body = body
           
        let imageName = "logo"
        guard let imageURL = Bundle.main.url(forResource: imageName, withExtension: "png") else { return }
        let attachment = try! UNNotificationAttachment(identifier: imageName, url: imageURL, options: .none)
        content.attachments = [attachment]
    }


Step 6: After that set the trigger for the notification to get fired. In our example, we define a certain time interval. But you can also use an UNCalendarNotificationTrigger or an UNLocationNotificationTrigger.

func sendNotification(title: String, subtitle: String?, body: String, launchIn: Double) {
        
        //...
           
        let trigger = UNTimeIntervalNotificationTrigger(timeInterval: launchIn, repeats: false)
        let request = UNNotificationRequest(identifier: "demoNotification", content: content, trigger: trigger)

    }


Step 7: Then, add the resulting request the the UNNotificationCenter. Once the defined time interval has lapsed, the notification gets fired!

func sendNotification(title: String, subtitle: String?, body: String, launchIn: Double) {
        
        //...

        UNUserNotificationCenter.current().add(request, withCompletionHandler: nil)
    }


Step 8 and 9: In our example SwiftUI app, we want to launch the local notification when tapping on a button. To do this, initialise the LocalNotificationManager and use its sendNotification method.

struct ContentView: View {
    
    //8. Observe the notification manager in your SwiftUI view
    @ObservedObject var notificationManager = LocalNotificationManager()
    
    @State var showFootnote = false
    
    var body: some View {
        NavigationView {
            VStack {
                Button(action: {
                    withAnimation {
                        self.showFootnote.toggle()
                        //9. Use the send notification function
                        self.notificationManager.sendNotification(title: "Hurray!", subtitle: nil, body: "If you see this text, launching the local notification worked!", launchIn: 5)
                    }
                }) {
                    Text("Launch Local Notification 🚀")
                        .font(.title)
                }
                if showFootnote {
                    Text("Notification Arrives in 5 seconds")
                        .font(.footnote)
                }
            }
                .navigationBarTitle("Local Notification Demo", displayMode: .inline)
        }
    }
}


If we now run our SwiftUI app, launch the local notification and close the app, we see that the notification gets fired as expected!


I hope you enjoyed this tutorial! If you want to learn more about SwiftUI, make sure you check out our free SwiftUI Basics eBook and our other tutorials! Also make sure you follow us on Instagram and subscribe to our newsletter to not miss any updates, tutorials and tips about SwiftUI and more!

3 replies on “How to use Local Notifications in SwiftUI”

Sure it’s more appropriate for the specific operation. This was just a sample trigger for the purpose of showing how to use SwiftUI local notifications in general (: Could you point out what exactly you are not understanding?

How do you deliver dynamic information at a regular interval? It looks like the content is set when you add the request and that you can’t update it.

I have tried playing around with notification controller and notification view with no luck.

Leave a Reply

Your email address will not be published. Required fields are marked *

small_c_popup.png

Covid-19 Forces you into quarantine?

Start Mastering swiftUI Today save your 33% discount

small_c_popup.png

Are you ready for a new era of iOS development?

Start learning swiftUI today - download our free e-book