Local push notification in iOS

Tram Ho

Have you ever wondered: I do not know about Backend, but want to write an application that can push notifications to users, is there any other way? Sure we have. You can use iOS’s Local push notification.
Local push notification is suitable for creating available schedules to notify users like reminders to do something.
In this article, I will guide you to configure and test a demo of local push notification.

Project creation

Open Xcode, and create a new Single View App.

Next, I enter the name and related information and click Next to create a project.

The interface is very simple, I just let one button send notification.

Apply for user rights

Surely, asking for user rights to push notification is very familiar to you.

Send notifications

To send notifications, I will create an instant of UNMutableNotificationContent. The UNMutableNotificationContent object contains the data of the message to be displayed, including title, body, subtitle.

To add Media content, please use UNNotificationAttachment.

Trigger

The trigger is how I specify the conditions for sending notifications. There are 3 types of triggers:

  • UNTimeIntervalNotificationTrigger: Specifies the time that the message will be emitted. For example, a notification will be generated every 5 seconds.
  • UNCalendarNotificationTrigger: Specify a notification date and time. The example specifies that December 18, 2020, will issue a notice.
  • UNLocationNotificationTrigger: Specifies where to send the message.

In this article, I will use UNTimeIntervalNotificationTrigger after 5 seconds will emit a notification and do not repeat the message.

One thing to note if you want to repeat the message then the timeInterval must be greater than 60 seconds. Otherwise the app will crash.

Create a request

To create a request, I use UNNotificationRequest . Then use UNUserNotificationCenter to schedule the sending.

Build and run the application, Click on Send Local push notification and wait for the result.

Good luck.

Share the news now

Source : Viblo