Задача: вывести уведомление о событии пользователю.
Решение:
1. Сначала попросим у пользователя разрешить получать уведомления:
|
override func viewDidLoad() { super.viewDidLoad() //requesting for authorization UNUserNotificationCenter.current().requestAuthorization(options: [.alert, .sound, .badge], completionHandler: {didAllow, error in }) } |
2. Оформим вывод уведомления через функцию:
|
func showNotify(title:String,subtitle:String,body:String,interval:TimeInterval){ let content = UNMutableNotificationContent() content.title = title content.subtitle = subtitle content.body = body content.badge = 1 let trigger = UNTimeIntervalNotificationTrigger(timeInterval: interval, repeats: false) let request = UNNotificationRequest(identifier: "SimplifiedIOSNotification", content: content, trigger: trigger) UNUserNotificationCenter.current().delegate = self UNUserNotificationCenter.current().add(request, withCompletionHandler: nil) } |
3. Нужно помнить, что уведомление в IOS<10 выводится только в том случае, если приложение «свернуто». Поэтому реализуем вывод уведомления, даже
если приложение открыто:
|
class ViewController: UIViewController, UNUserNotificationCenterDelegate { func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) { //displaying the ios local notification when app is in foreground completionHandler([.alert, .badge, .sound]) } |