Add Local Notification in iOS 10 - Swift 3

Add Local Notification in iOS 10 - Swift 3

You need to register for Notification...I tried and this works.

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
// Override point for customization after application launch.
let center = UNUserNotificationCenter.current()
center.requestAuthorization([.alert, .sound]) { (granted, error) in
// Enable or disable features based on authorization.
}
return true
}

Edit: You dont need to put your app in background to present notification from iOS 10 onwards.

Use below callback to configure notification to present in foreground.

func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void)

Here is a sample project.

Local notification in swift 3 with new UI

The red and blue buttons are only available in iOS versions prior to iOS 10. With iOS 10 the notifications design changed. The slide gesture is used for the standard actions Clear and View. The custom actions Snooze and Confirm will be displayed when you force touch the notification or pull it down (for devices without force touch). If you are using a device with force touch the View button might not be shown.

The buttons look different now:

Sample Image

So, here is how you implement Local Notifications with Swift 3 / 4:

For iOS versions prior to iOS 10:

If you are supporting iOS versions prior to iOS10 you have to use the old (deprecated with iOS 10) UILocalNotification:

class AppDelegate: UIResponder, UIApplicationDelegate {

var window: UIWindow?

func application(_ application: UIApplication, willFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey : Any]? = nil) -> Bool {
registerLocalNotification()
return true
}

func applicationWillResignActive(_ application: UIApplication) {
scheduleLocalNotification()
}

func scheduleLocalNotification() {
let localNotification = UILocalNotification()
localNotification.alertTitle = "Buy milk"
localNotification.alertBody = "Remember to buy milk from store"
localNotification.fireDate = Date(timeIntervalSinceNow: 3)
localNotification.soundName = UILocalNotificationDefaultSoundName
localNotification.category = "reminderCategory" // Category to use the specified actions
UIApplication.shared.scheduleLocalNotification(localNotification) // Scheduling the notification.
}

func registerLocalNotification() {
let reminderActionConfirm = UIMutableUserNotificationAction()
reminderActionConfirm.identifier = "Confirm"
reminderActionConfirm.title = "Confirm"
reminderActionConfirm.activationMode = .background
reminderActionConfirm.isDestructive = false
reminderActionConfirm.isAuthenticationRequired = false

let reminderActionSnooze = UIMutableUserNotificationAction()
reminderActionSnooze.identifier = "Snooze"
reminderActionSnooze.title = "Snooze"
reminderActionSnooze.activationMode = .background
reminderActionSnooze.isDestructive = true
reminderActionSnooze.isAuthenticationRequired = false

// Create a category with the above actions
let shoppingListReminderCategory = UIMutableUserNotificationCategory()
shoppingListReminderCategory.identifier = "reminderCategory"
shoppingListReminderCategory.setActions([reminderActionConfirm, reminderActionSnooze], for: .default)
shoppingListReminderCategory.setActions([reminderActionConfirm, reminderActionSnooze], for: .minimal)

// Register for notification: This will prompt for the user's consent to receive notifications from this app.
let notificationSettings = UIUserNotificationSettings(types: [.alert, .sound, .badge], categories: [shoppingListReminderCategory])

UIApplication.shared.registerUserNotificationSettings(notificationSettings)
}
}

This will register the local notification and fires it 3 seconds after the user closes the app (for testing purposes)

For iOS 10 and later:

If you target your app to iOS 10 you can use the new UserNotifications framework:

import UIKit
import UserNotifications

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {

var window: UIWindow?

func application(_ application: UIApplication, willFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey : Any]? = nil) -> Bool {
registerUserNotifications()
return true
}

func applicationWillResignActive(_ application: UIApplication) {
scheduleLocalNotification()
}

func registerUserNotifications() {
UNUserNotificationCenter.current().requestAuthorization(options: [.alert, .sound, .badge]) { (granted, error) in
guard granted else { return }
self.setNotificationCategories()
}
}

func setNotificationCategories() {
// Create the custom actions
let snoozeAction = UNNotificationAction(identifier: "SNOOZE_ACTION",
title: "Snooze",
options: .destructive)
let confirmAction = UNNotificationAction(identifier: "CONFIRM_ACTION",
title: "Confirm",
options: [])

let expiredCategory = UNNotificationCategory(identifier: "TIMER_EXPIRED",
actions: [snoozeAction, confirmAction],
intentIdentifiers: [],
options: UNNotificationCategoryOptions(rawValue: 0))

// Register the category.
let center = UNUserNotificationCenter.current()
center.setNotificationCategories([expiredCategory])
}

func scheduleLocalNotification() {
let content = UNMutableNotificationContent()
content.title = "Buy milk!"
content.body = "Remember to buy milk from store!"
content.categoryIdentifier = "TIMER_EXPIRED"

let trigger = UNTimeIntervalNotificationTrigger(timeInterval: 3, repeats: false)

// Create the request object.
let request = UNNotificationRequest(identifier: "Milk reminder", content: content, trigger: trigger)

// Schedule the request.
let center = UNUserNotificationCenter.current()
center.add(request) { (error : Error?) in
if let theError = error {
print(theError.localizedDescription)
}
}
}
}

You can check out a demo app that uses the UserNotifications framework here

Add Custom Local Notification in ios10 - swift 3

Update: As of iOS 10 beta 2, rich notifications are also available on pre-3D touch devices. Pull down on the regular notification to see it.

Make sure you are testing on a iPhone6s/iPhone6s plus simulator/device, it doesn't seem to work on pre-3D touch devices.

On a iPhone6 simulator, try to click and drag down on the stock notification you get and you should see your custom UI appear.

Local Notifications swift 3

When you create notification at that check

 if #available(iOS 10.0, *) {
let content = UNMutableNotificationContent()
content.title = "Intro to Notifications"
content.subtitle = "Lets code,Talk is cheap"
content.body = "Sample code from WWDC"
content.sound = UNNotificationSound.default()
// Deliver the notification in five seconds.
let trigger = UNTimeIntervalNotificationTrigger.init(timeInterval: 5.0, repeats: false)
let request = UNNotificationRequest(identifier:requestIdentifier, content: content, trigger: trigger)

UNUserNotificationCenter.current().delegate = self
UNUserNotificationCenter.current().add(request){(error) in

if (error != nil){

print(error?.localizedDescription)
}
}
}

Implement this delegates method UNUserNotification for Notification being triggered.

@available(iOS 10.0, *)
func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) {

print("Tapped in notification")
}


//This is key callback to present notification while the app is in foreground
@available(iOS 10.0, *)
func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {

print("Notification being triggered")
//You can either present alert ,sound or increase badge while the app is in foreground too with ios 10
//to distinguish between notifications
if notification.request.identifier == requestIdentifier{

completionHandler( [.alert,.sound,.badge])

}
}

Happy coding.

Sending local notifications in SWIFT

The notification comes but when the app is foreground it won't show until you implement UNUserNotificationCenterDelegate method

UNUserNotificationCenter.current().delegate = self


func userNotificationCenter(_ center: UNUserNotificationCenter,
willPresent notification: UNNotification,
withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
completionHandler([.sound,.alert])
}

Also set

 let date = Date().addingTimeInterval(5)

to give it some time until app hits so you can test it after clicking home button

import UIKit

class ViewController: UIViewController , UNUserNotificationCenterDelegate {

override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.


let center = UNUserNotificationCenter.current()
center.delegate = self
center.requestAuthorization(options: [.badge,.sound,.alert]) { granted, error in
if error == nil {
print("User permission is granted : \(granted)")
}
}
// Step-2 Create the notification content
let content = UNMutableNotificationContent()
content.title = "Hello"
content.body = "Welcome"


// Step-3 Create the notification trigger
let date = Date().addingTimeInterval(5)
let dateComponent = Calendar.current.dateComponents([.year,.month,.day,.hour,.minute,.second], from: date)
let trigger = UNCalendarNotificationTrigger(dateMatching: dateComponent, repeats: false)



// Step-4 Create a request
let uuid = UUID().uuidString
let request = UNNotificationRequest(identifier: uuid, content: content, trigger: trigger)


// Step-5 Register with Notification Center
center.add(request) { error in


}
}

func userNotificationCenter(_ center: UNUserNotificationCenter,
willPresent notification: UNNotification,
withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
completionHandler([.sound,.alert])
}

}

Repeating local notifications for specific days of week (Swift 3 IOS 10)

You can use below function to get Date from selected picker value:

    //Create Date from picker selected value.
func createDate(weekday: Int, hour: Int, minute: Int, year: Int)->Date{

var components = DateComponents()
components.hour = hour
components.minute = minute
components.year = year
components.weekday = weekday // sunday = 1 ... saturday = 7
components.weekdayOrdinal = 10
components.timeZone = .current

let calendar = Calendar(identifier: .gregorian)
return calendar.date(from: components)!
}

//Schedule Notification with weekly bases.
func scheduleNotification(at date: Date, body: String, titles:String) {

let triggerWeekly = Calendar.current.dateComponents([.weekday,.hour,.minute,.second,], from: date)

let trigger = UNCalendarNotificationTrigger(dateMatching: triggerWeekly, repeats: true)

let content = UNMutableNotificationContent()
content.title = titles
content.body = body
content.sound = UNNotificationSound.default()
content.categoryIdentifier = "todoList"

let request = UNNotificationRequest(identifier: "textNotification", content: content, trigger: trigger)

UNUserNotificationCenter.current().delegate = self
//UNUserNotificationCenter.current().removeAllPendingNotificationRequests()
UNUserNotificationCenter.current().add(request) {(error) in
if let error = error {
print("Uh oh! We had an error: \(error)")
}
}
}

After getting a value from picker pass picker hour, minute and year with selected week day as (Sunday = 1, Monday = 2, Tuesday = 3, Wednesday = 4, thursday = 5, Friday = 6, Saturday = 7) to function func createDate(weekday: Int, hour: Int, minute: Int, year: Int) to get notification fire date on weekly bases, and after getting date call function func scheduleNotification(at date: Date, body: String, titles:String) for schedule a notification.



Related Topics



Leave a reply



Submit