Basic use of iOS local push notifications

Local Notification before iOS 10

Steps to use:

  1. Create a UILocalNotification object
  2. Set trigger time and title, content
  3. Register and schedule notifications
// 1. Create a UILocalNotification object
let localNotification = UILocalNotification()

// 2. Set trigger time, title and content
localNotification.fireDate = Date(timeIntervalSinceNow: 3)
localNotification.alertTitle = "Title"
localNotification.alertBody = "alertBodyalertBodyalertBodyalertBody"

// 0. Registration Notifications (typically when a program is just started)
UIApplication.shared.registerUserNotificationSettings(UIUserNotificationSettings(types: [.badge, .alert, .sound], categories: nil))

// 3. Arrange notifications
UIApplication.shared.scheduleLocalNotification(localNotification)
  • Other properties of UILocalNotification

    • applicationIconBadgeNumber: A numeric marker on the application icon
    • RepatInterval: Repeat interval (by year, month, day, hour, minute)
    • soundName: Prompt sound for notification, using UILocalNotificationDefaultSoundName or specified audio file name
    • userInfo: Extra dictionary related to notifications that users cannot see on notifications

Application handles notifications received

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
    // ......
    
    // Click notification to start the program (program is not in the foreground or background, that is, when the program exits), where you can get the clicked notification and process it
    if let localNotification = launchOptions?[.localNotification] {
        print(localNotification)
    }
    
    return true
}

// When an application receives a notification, it handles it in this way
func application(_ application: UIApplication, didReceive notification: UILocalNotification) {
    print(notification)
}

iOS10+ uses UNNotificationRequest to create local notifications

Use steps

  1. Request Authorization
  2. Create Notification Content
  3. Create Notification Trigger Time
  4. Create notification request using unique identification string, content, trigger
  5. Add notification request to notification Center
// 1. Create Notification Content
let content = UNMutableNotificationContent()
// Title
content.title = NSString.localizedUserNotificationString(forKey: "Hello!", arguments: nil)
// content
content.body = NSString.localizedUserNotificationString(forKey: "Hello_message_body", arguments: nil)
// Notification alert tone
content.sound = .default
 
// 2. Create notification triggers
// Deliver the notification in five seconds.
let trigger = UNTimeIntervalNotificationTrigger(timeInterval: 5, repeats: false)


// 3. Create notification requests using unique identification strings, content, triggers
let uuidString = UUID().uuidString
let request = UNNotificationRequest(identifier: uuidString, content: content, trigger: trigger)


// Get the notification Center for the current program
let notificationCenter = UNUserNotificationCenter.current()
// Set up a proxy to handle notifications received
notificationCenter.delegate = self
// 0. Request authorization (usually notify authorization when a program has just started)
notificationCenter.requestAuthorization(options: [.alert, .badge, .sound]) { (granted, error) in
    
}

// 4. Add notification request to notification Center
notificationCenter.add(request) { (error) in
    if error != nil {
       // Handle any errors.
    }
}
  • Other common properties of UNMutableNotificationContent

    • Subtitle: subtitle
    • badge: a numeric marker on the application icon
    • userInfo: Extra dictionary related to notifications that users cannot see on notifications
  • Common notification triggers for UNNotificationTrigger

    • UNTimeIntervalNotificationTrigger: Triggers after a few seconds, if you want to set a repeatable trigger it needs to be greater than 60
    • UNCalendarNotificationTrigger: Triggered at a time, a minute, a second, a day, a month, a year
    • UNLocationNotificationTrigger: Trigger at a location
  • Processing received notifications (using two methods in UNUserNotificationCenterDelegate)
// Asks the delegate to process the user's response to a delivered notification.
func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) {
    // Processing Code
    ......
    completionHandler()
}

// This method handles notifications received while the application is running in the foreground
func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
    // Processing Code
    ......
    completionHandler(.sound)
}

Tags: iOS

Posted on Sat, 16 May 2020 12:42:45 -0400 by simpli