Well, in iOS 10, Apple has deprecated UILocalNotification, which means it's time to familiarize yourself with the new notification system.
Customization This is a long post, so you can easily start by importing a new notification structure:
// Swift import UserNotifications // Objective-C (with modules enabled) @import UserNotifications;
Managing notifications through a common UNUserNotificationCenter object:
// Swift let center = UNUserNotificationCenter.current() // Objective-C UNUserNotificationCenter *center = [UNUserNotificationCenter currentNotificationCenter];
Authorization As with the earlier notification structure, you must have user permission for the types of notifications that your application will use. Make a request at an early stage in your application life cycle, for example in the application: didFinishLaunchingWithOptions :. The first time you authorize your application, the system displays a warning to the user, after which they can manage permissions from the settings:
// Swift let options: UNAuthorizationOptions = [.alert, .sound]; // Objective-C UNAuthorizationOptions options = UNAuthorizationOptionAlert + UNAuthorizationOptionSound;
You make the actual authorization request using the general notification center:
// Swift center.requestAuthorization(options: options) { (granted, error) in if !granted { print("Something went wrong") } } // Objective-C [center requestAuthorizationWithOptions:options completionHandler:^(BOOL granted, NSError * _Nullable error) { if (!granted) { NSLog(@"Something went wrong"); } }];
The structure calls a termination handler with a boolean indicating whether access was granted and an error object that will be zero if no error occurs.
Note. The user can change the notification settings for your application at any time. You can check the allowed settings using the getNotificationSettings method. This asynchronously calls the termination block with the UNNotificationSettings object, which you can use to check the authorization status or individual notification settings:
// Swift center.getNotificationSettings { (settings) in if settings.authorizationStatus != .authorized { // Notifications not allowed } } // Objective-C [center getNotificationSettingsWithCompletionHandler:^(UNNotificationSettings * _Nonnull settings) { if (settings.authorizationStatus != UNAuthorizationStatusAuthorized) { // Notifications not allowed } }];
Creating a notification request The notification request UNNotificationRequest contains the content and trigger condition:
Notification Content
The contents of the notification is an instance of the UNMutableNotificationContent object with the following parameters set as necessary:
title: A string containing the root cause of the warning.
subtitles: a string containing warning subtitles (if required)
body: String containing the text of the warning message
Icon
: number to display on the application icon.
sound: the sound that will be played when an alert is given. Use UNNotificationSound.default () or create a custom sound from a file. launchImageName: The name of the launch image that will be used when the application starts in response to a notification.
userInfo: a dictionary of user information to pass in the notification Attachments: an array of UNNotificationAttachment objects. Use to enable audio, image or video content.
Note that when localizing warning lines, such as a header, it is better to use localizedUserNotificationString (forKey: arguments :), which delays loading localization until a notification is sent.
Quick example:
// Swift let content = UNMutableNotificationContent() content.title = "Don't forget" content.body = "Buy some milk" content.sound = UNNotificationSound.default() // Objective-C UNMutableNotificationContent *content = [UNMutableNotificationContent new]; content.title = @"Don't forget"; content.body = @"Buy some milk"; content.sound = [UNNotificationSound defaultSound];
Notification alert
Start notifications about time, calendar or location. The trigger can be repeated:
Time Interval: Schedule a notification a few seconds later. For example, to start in five minutes:
// Swift let trigger = UNTimeIntervalNotificationTrigger(timeInterval: 300, repeats: false) // Objective-C UNTimeIntervalNotificationTrigger *trigger = [UNTimeIntervalNotificationTrigger triggerWithTimeInterval:300 repeats:NO];
Calendar: Launch at a specific date and time. A trigger is created using the date component component, which simplifies some recurring intervals. To convert a date to its date, components use the current calendar. For example:
// Swift let date = Date(timeIntervalSinceNow: 3600) let triggerDate = Calendar.current.dateComponents([.year, .month, .day, .hour, .minute, .second], from: date) // Objective-C NSDate *date = [NSDate dateWithTimeIntervalSinceNow:3600]; NSDateComponents *triggerDate = [[NSCalendar currentCalendar] components:NSCalendarUnitYear + NSCalendarUnitMonth + NSCalendarUnitDay + NSCalendarUnitHour + NSCalendarUnitMinute + NSCalendarUnitSecond fromDate:date];
To create a trigger from date components:
// Swift let trigger = UNCalendarNotificationTrigger(dateMatching: triggerDate, repeats: false) // Objective-C UNCalendarNotificationTrigger *trigger = [UNCalendarNotificationTrigger triggerWithDateMatchingComponents:triggerDate repeats:NO];
To create a trigger that repeats at a specific interval, use the correct set of date components. For example, for the daily notification to be repeated, we only need an hour, minutes and seconds:
let triggerDaily = Calendar.current.dateComponents([hour, .minute, .second], from: date) let trigger = UNCalendarNotificationTrigger(dateMatching: triggerDaily, repeats: true)
To repeat weekly at the same time, we also need a weekday:
let triggerWeekly = Calendar.current.dateComponents([.weekday, .hour, .minute, .second], from: date) let trigger = UNCalendarNotificationTrigger(dateMatching: triggerWeekly, repeats: true)
Planning
In preparing the content and trigger, we create a new notification request and add it to the notification center. For each notification request, a line identifier is required for future reference:
// Swift let identifier = "UYLLocalNotification" let request = UNNotificationRequest(identifier: identifier, content: content, trigger: trigger) center.add(request, withCompletionHandler: { (error) in if let error = error { // Something went wrong } }) // Objective-C NSString *identifier = @"UYLLocalNotification"; UNNotificationRequest *request = [UNNotificationRequest requestWithIdentifier:identifier content:content trigger:trigger] [center addNotificationRequest:request withCompletionHandler:^(NSError * _Nullable error) { if (error != nil) { NSLog(@"Something went wrong: %@",error); } }];