Easily create Local Notifications in swift - Wrapper of UserNotifications Framework

Overview

Swift Version CocoaPods Compatible Platform Build Status License

In IOS 10, apple updated their library for Notifications and separated Local and push notifications to a new framework:

User Notifications

This library makes it easy to setup a local notification and also includes easy configuration for repeating notifications using [ .None, .Minute, .Hourly, .Daily, .Monthly, .Yearly] .

It also includes all the new features, including inserting attachments and changing the launch image of a notification.

  1. Features
  2. Requirements
  3. Installation
  4. Usage
  5. Contribute

Features

  • Easily Repeat Notifications
  • Location Based Notifications
  • Category Action buttons
  • Queue to enforce 64 notification limit

Requirements

  • iOS 10.0+
  • Xcode 8.0+

Installation

CocoaPods

You can use CocoaPods to install DLLocalNotifications by adding it to your Podfile:

platform :ios, '10.0'
use_frameworks!

target 'MyApp' do
	pod 'DLLocalNotifications'
end

Note: your iOS deployment target must be 10.0+

Usage

Single fire notification (any date)

Notification that fires once at the date time inputted

Note: If you want the notification to repeat then you need to create a notification based on date components

// The date you would like the notification to fire at
let triggerDate = Date().addingTimeInterval(300)

let firstNotification = DLNotification(identifier: "firstNotification", alertTitle: "Notification Alert", alertBody: "You have successfully created a notification", date: triggerDate)

let scheduler = DLNotificationScheduler()
scheduler.scheduleNotification(notification: firstNotification)
scheduler.scheduleAllNotifications()

Repeating Notification based on date components

The configuration of the repetition is chosen in the repeats parameter that can be [ .none, .minute, .hourly, .daily, .monthly, .yearly] .

// The date you would like the notification to fire at :35 mins every hour

var dateComponents = DateComponents()
dateComponents.minute = 35
dateComponents.second = 0

let firstNotification = DLNotification(identifier: "hourlyNotification", alertTitle: "Notification Alert", alertBody: "You have successfully created a notification", fromDateComponents: dateComponents, repeatInterval: .hourly)

let scheduler = DLNotificationScheduler()
scheduler.scheduleNotification(notification: firstNotification)
scheduler.scheduleAllNotifications()

Notification that repeats from one Date to another with a time interval period

This is useful to setup notifications to repeat every specific time interval for in a specific time period of the day.

let scheduler = DLNotificationScheduler()

// This notification repeats every 15 seconds from a time period starting from 15 seconds from the current time till 5 minutes from the current time

scheduler.repeatsFromToDate(identifier: "First Notification", alertTitle: "Multiple Notifications", alertBody: "Progress", fromDate: Date().addingTimeInterval(15), toDate: Date().addingTimeInterval(300) , interval: 15, repeats: .none )
scheduler.scheduleAllNotifications()

Note: Since this library takes care of the 64 notification limit you would want to call scheduler.scheduleAllNotifications() in your AppDelegate file as well.

Modifying elements of the notification

You can modify elements of the notification before scheduling. Publically accessible variables include:

repeatInterval, alertBody, alertTitle, soundName, fireDate, attachments, launchImageName, category

let firstNotification = DLNotification(identifier: "firstNotification", alertTitle: "Notification Alert", alertBody: "You have successfully created a notification", date: Date(), repeats: .minute)

// You can now change the repeat interval here
firstNotification.repeatInterval = .yearly

// You can add a launch image name
firstNotification.launchImageName = "Hello.png"

let scheduler = DLNotificationScheduler()
scheduler.scheduleNotification(notification: firstNotification)
scheduler.scheduleAllNotifications()

Location Based Notification

The notification is triggered when a user enters a geo-fenced area.

let center = CLLocationCoordinate2D(latitude: 37.335400, longitude: -122.009201)
let region = CLCircularRegion(center: center, radius: 2000.0, identifier: "Headquarters")
region.notifyOnEntry = true
region.notifyOnExit = false

let locationNotification = DLNotification(identifier: "LocationNotification", alertTitle: "Notification Alert", alertBody: "You have reached work", region: region )

let scheduler = DLNotificationScheduler()
scheduler.scheduleNotification(notification: locationNotification)
scheduler.scheduleAllNotifications()

Adding action buttons to a notification

 let scheduler = DLNotificationScheduler()

 let standingCategory = DLCategory(categoryIdentifier: "standingReminder")

 standingCategory.addActionButton(identifier: "willStand", title: "Ok, got it")
 standingCategory.addActionButton(identifier: "willNotStand", title: "Cannot")

 scheduler.scheduleCategories(categories: [standingCategory])

Don't forget to the set the notification category before scheduling the notification using

notification.category = "standingReminder"

Cancelling a notification

 scheduler.cancelNotification(notification: notification)

Contribute

We would love for you to contribute to DLLocalNotifications, check the LICENSE file for more info.

Meta

Devesh Laungani – @d7laungani

Distributed under the MIT license. See LICENSE for more information

https://github.com/d7laungani/

Hire Me

Comments
  • Not showing Action Button

    Not showing Action Button

    Im trying to show action buttons with the notification

    ` func dailyNotification(){

        let firstNotification = DLNotification(identifier: "firstNotification", alertTitle: "Notificaiton Alert", alertBody: "You have successfully created a notification", date: Date(), repeats: .Minute)
        
        // You can now change the repeat interval here
        firstNotification.repeatInterval = .Minute
        
        // You can add a launch image name
        firstNotification.launchImageName = "logo_ad.jpg"
        
        let scheduler = DLNotificationScheduler()
       
        let standingCategory = DLCategory(categoryIdentifier: "standingReminder")
        
        standingCategory.addActionButton(identifier: "willStand", title: "Ok, got it")
        standingCategory.addActionButton(identifier: "willNotStand", title: "Cannot")
        
        scheduler.scheduleCategories(categories: [standingCategory])
        scheduler.scheduleNotification(notification: firstNotification)
        firstNotification.category = "standingReminder"
    }`
    

    any reason why this isnt working

    thank you

    opened by n4zg 5
  • firstNotification.launchImageName not working

    firstNotification.launchImageName not working

    Hi,

    I would like to add an image on the localnotification but i've got this error: 'launchImageName' is inaccessible due to 'internal' protection level

    Can you help me to fix it please ?

    Thanks in advance

    opened by fabien79 2
  • Crash when set Date to nil

    Crash when set Date to nil

    Crash at:

    https://github.com/d7laungani/DLLocalNotifications/blob/e4e483e13b16af0fb5f65618f6347f0d3aa0bee5/DLLocalNotifications/DLLocalNotifications.swift#L117

    by following code

    let notification = DLNotification(identifier: "", alertTitle: "", alertBody: "", date: nil, repeats: .none, soundName: "")
    let scheduler = DLNotificationScheduler()
    scheduler.scheduleNotification(notification: notification)
    scheduler.scheduleAllNotifications()
    
    opened by Haraguroicha 2
  • podfile install issue

    podfile install issue

    I have an issue installing this from the master branch.

    When i run 'pod install' on the app with the line pod 'DLLocalNotifications', '~>0.06' in my podfile, I get the following line of code

    content.sound = (notification.soundName == nil) ? UNNotificationSound.default() : UNNotificationSound.init(named: notification.soundName!)

    However, I noticed that this is replaced by

    content.sound = notification.soundName == "" ? UNNotificationSound.default : UNNotificationSound.init(named: UNNotificationSoundName(rawValue: notification.soundName))

    in the actual code. Why would the pod install of mine have the wrong line of code in it?

    opened by raguiar2 2
  • How to schedule a notification that will repeat with some frequency after specific time passes

    How to schedule a notification that will repeat with some frequency after specific time passes

    I don't see support for scheduling such kind of notification i.e. that repeats only when a specific time passes. The problem is that the schedule fires immediately without waiting for the exact time although repeats correctly.

    e.g. here is the code for scheduling a repeating notification after 10 minutes. This doesn't wait for the 10 minutes - fires immediately in the next minute from now.

        let triggerDate = Date().addingTimeInterval(600)
        let firstNotification = DLNotification(identifier: "firstNotification", alertTitle: "Notification Alert",                        alertBody: "You have successfully created a notification", date: triggerDate, repeats: .Minute)
        
        let scheduler = DLNotificationScheduler()
        scheduler.scheduleNotification(notification: firstNotification)
    

    here is another block of code for a repeating notification that will fire daily after 3 days.

        let triggerDate = Date().addingTimeInterval(3*24*60*60)
        let firstNotification = DLNotification(identifier: "firstNotification", alertTitle: "Notification Alert", alertBody: "You have successfully created a notification", date: triggerDate, repeats: .Daily)
        
        let scheduler = DLNotificationScheduler()
        scheduler.scheduleNotification(notification: firstNotification)`
    

    This also doesn't wait for the 3 days but fires immediately on the next day.

    The main problem in both is that it ignores the time till which it should wait to start firing the notification. If anybody has understood the problem, will you take some time to figure out what's wrong. I will be really thankful.

    opened by mibrahim025 2
  • Help me! Support required

    Help me! Support required

    I have 3 local notifications need to be repeated daily from (9am to 6pm with frequency of 3 hrs), I used repeatsFromToDate() but it didn't work.

    Note:- There are 3 LocalNotification with the different startTime& endTime & user can stop/start any of these at anytime.

    I need to repeat it 3-4 times a day till the user turns off the notification (ie., 10AM, 1PM, 4PM, 7PM today, tomorrow... ) - this is for notification1, similarly the app has 2 similar notifications (Notification2 might trigger at 9AM, 12PM, 3PM, 6PM today, tomorrow... Notification3- 4PM, 10PM today, tomorrow...). How to repeat them daily between these time intervals? Again user can't change the frequency, he could change the start & end time for each notifications or turn off.

    opened by nagarajavrao 1
  • made identifier public

    made identifier public

    I need this for the functionality in my app- I uniquely generate the identifiers and can get groups of notifications by a specific prefix.

    Fixes issue https://github.com/d7laungani/DLLocalNotifications/issues/19

    opened by raguiar2 1
  • Added a notificationsQueue function to get all queued notificaitons

    Added a notificationsQueue function to get all queued notificaitons

    I noticed that it was difficult to reschedule notifications after they had been queued. This change will allow you to retrieve all notifications from the queue, and then

    opened by raguiar2 1
  • unexpectedly found nil while unwrapping an Optional value

    unexpectedly found nil while unwrapping an Optional value

    let scheduler = DLNotificationScheduler() let standingCategory = DLCategory(categoryIdentifier: "standingReminder") standingCategory.addActionButton(identifier: "willStand", title: "Ok, got it") standingCategory.addActionButton(identifier: "willNotStand", title: "Cannot") scheduler.scheduleCategories(categories: [standingCategory])

    getting the following error fatal error: unexpectedly found nil while unwrapping an Optional value 2017-03-12 14:24:09.727084 fatal error: unexpectedly found nil while unwrapping an Optional value

    any suggestions please

    opened by n4zg 1
  • Fix bugs

    Fix bugs

    This PR fixes multiple issues and refactors the API to better reflect the limitations of the User Notifications Framework

    Notes -- You can only repeat notifications via date components -- Delayed repeated notifications are not supported in the underlying User Notifications Framework

    opened by d7laungani 0
  • Support required

    Support required

    After scheduling multiple notifications using the method scheduler.repeatsFromToDate (repeats between start & end time) , i cant stop a particular notification.

    Requirement:-1. Start multiple notifications(one at a time) with the changeable start time, end time & range. 2. stop a particular notification.

    Could you help

    opened by nagarajavrao 0
  • repeat interval minute is not working

    repeat interval minute is not working

    when i schedule notifications with from date and to date with repeat interval minute, it is not start firing notification at from date instead it start immediately.

    opened by Sweta53 0
  • if i can change interval to less than 10 seconds than notification not work on specific time

    if i can change interval to less than 10 seconds than notification not work on specific time

    i want to fire notification between specific time but interval is 2/3 seconds not 10/15 seconds so i do following changes but it will not work , not fire notification on perfect start time time.

    let scheduler = DLNotificationScheduler() scheduler.repeatsFromToDate(identifier: "First Notification", alertTitle: "Multiple Notifications", alertBody: "Progress", fromDate: Date(), toDate: Date().addingTimeInterval(300) , interval: 10, repeats: .none ) scheduler.scheduleAllNotifications()

    opened by niravparmar231 0
  • Fire Notification Daily but After a certain date

    Fire Notification Daily but After a certain date

    I want to set a repeat Local notification from date. For Example:

    StartDate: 26-July-2022

    Todays Date: 23-July-2022

    I am stuck here. I want to set a repeat Local notification from date.

    Please have a look to my Notification function:

    func scheduleLocalNotification(date: Date) {
            var calendar = Calendar.current
            calendar.timeZone = TimeZone.current
    
            let content = UNMutableNotificationContent()
            // Configure Notification Content
            content.title = "REMINDER For Yoga"
            content.body = "Hi! Take ready for Daily Yoga Class."
    
            // Set Category Identifier
            content.categoryIdentifier =  "Yoga_872"
            var components = calendar.dateComponents([.hour, .minute], from: date)
    
            let trigger = UNCalendarNotificationTrigger(dateMatching: components, repeats: true)
           
            // Create Notification Request
            let identifier = "Yoga_Class(222)"
    
            let notificationRequest = UNNotificationRequest(identifier: identifier, content: content, trigger: trigger)
    
            // Add Request to User Notification Center
            UNUserNotificationCenter.current().add(notificationRequest) { (error) in
                if let error = error {
                    print("Add Notification Request Error:  (\(error), \(error.localizedDescription))")
                }           
            }
    
        }
    

    This function fire notification from Today. I want to this from 26th July 2022.

    opened by ErAshu 0
Releases(0.09)
Owner
Devesh Laungani
Full Stack Engineer
Devesh Laungani
See all your scheduled local notifications in one place

ScheduledNotificationsViewController Nice Photon is available for hire! Talk to

Nice Photon 171 Oct 8, 2022
Facebook Analytics In-App Notifications Framework

Facebook In-App Notifications enables you to create rich and customizable in-app notifications and deliver them via push notifications, based on the a

Meta Archive 496 Nov 17, 2022
Push notifications allow developers to reach users, even when users aren't actively using an app!

Push notifications allow developers to reach users, even when users aren't actively using an app! With the latest update of iOS Apple provide very useful extensions which are user-friendly. In this tutorial, I am going to share the configuration, set up of Notification with the media attachments like.

MindInventory 16 Mar 3, 2022
Library to send mock remote notifications to the iOS simulator

SimulatorRemoteNotifications SimulatorRemoteNotifications is a library to send mock remote notifications to the iOS simulator. The library extends UIA

Arnaud Coomans 1.4k Dec 20, 2022
Pushkin is a free open source tool for sending push notifications

Unmaintained This repository is no longer maintained. Pushkin Introduction Pushkin is a free open source tool for sending push notifications. It was d

Nordeus 257 Nov 3, 2022
Custom in-app notifications.

CRNotifications CRNotifications are custom in-app notifications with 3 types of layouts. The notifications will animate in and out. They will hide whe

Casper Riboe 112 Sep 2, 2022
Gently notifies you about 'important' GitHub notifications

OctoBlast Gently notifies you about important GitHub notifications Setup Personal access token Head to preferences, and pop in your a new GitHub perso

Jason Watson 6 Nov 14, 2022
How to Add Local Push Notification With timeInterval & Test On Simulator

Technicalisto How to Add Local Push Notification With timeInterval & Test On Simulator In Project Target ( Signing & Capapilities ) Add Capapility : 1

Aya Baghdadi 0 Jun 24, 2022
ToDoAppCoreData - MVVM + Core Data + Local Notification

ToDo App Features MVVM + Core Data + Local Notification Screen recordings Creadi

Watery Desert 22 Nov 28, 2022
A fully customizable library to easily display Animated Toast Messages in iOS using Swift!

CustomToastView-swift A fully customizable library to easily display Animated Toast Messages in iOS using Swift! Preview - All the custom toasts you c

Leticia Rodriguez 13 Aug 20, 2022
OS X and iOS application and framework to play with the Apple Push Notification service (APNs)

Pusher OS X and iOS application and framework to play with the Apple Push Notification service (APNs) Installation Install the Mac app using Homebrew

noodlewerk 6.2k Dec 22, 2022
🚎 Simple type-safe event bus implementation in swift

?? RealEventsBus RealEventsBus is a small swift experiment package to implement a basic type-safe event bus mechanism. Some other implementations in G

Daniele Margutti 12 Jul 19, 2022
A Swift Library for Dynamic Island Push Notification.

Push Notification With Dynamic Island Handle Push Notification with Dynamic Island ?? Descreption: Since there is not library for Apple Push Notificat

Amir Diafi 5 Nov 12, 2022
A simple framework to output to a file, url, the console, or even register notification using UserNotifications

o is a simple framework to output to a file, url, the console, or even register notification using UserNotifications. o can also get input from a file, url, or console.

OpenBytes 4 Mar 18, 2022
Joseph Miller 0 Jan 7, 2022
See all your scheduled local notifications in one place

ScheduledNotificationsViewController Nice Photon is available for hire! Talk to

Nice Photon 171 Oct 8, 2022
A framework for easily testing Push Notifications and Routing in XCUITests

Mussel ?? ?? A framework for easily testing Push Notifications, Universal Links and Routing in XCUITests. As of Xcode 11.4, users are able to test Pus

Compass 65 Dec 28, 2022
CoffeeToast - A swift package to easily add Toast notifications to your app

CoffeeToast A simple Swift package to add Toast Notifications to your app. Insta

Maegan Wilson 2 Feb 3, 2022
AutoMocker is a Swift framework that leverages the type system to let you easily create mocked instances of your data types.

AutoMocker Context AutoMocker is a Swift framework that leverages the type system to let you easily create mocked instances of your data types. Here's

Vincent Pradeilles 39 May 19, 2022
An iOS framework to easily create simple animated walkthrough, written in Swift.

Intro Overview An iOS framework to easily create simple animated walkthrough, written in Swift. Requirements iOS8 Installation with CocoaPods Intro is

Nurdaulet Bolatov 33 Oct 1, 2021