class NotificationService: NSObject, UNUserNotificationCenterDelegate { let notificationCenter = UNUserNotificationCenter.current() }
// 1 // , Tuple . // showBody - Bool, . // withAction - Bool, , "" . // atDate date - Date, , . func showNotification(with item: (String, String), showBody: Bool, withAction: Bool, atDate date: Date) { // 2 // let content = UNMutableNotificationContent() // 3 // let userActionsIdentifier = “showMe” // 4 // . content.title = item.0 // 5 // , false, , . if showBody { content.body = item.1 } // 6 // - notificationCenter userInfo . content.userInfo = [item.0: item.1] content.sound = UNNotificationSound.default // 7 // withAction true, "Show me". if withAction { content.categoryIdentifier = userActionsIdentifier } // 8 // , . let notificationID = item.0 // 9 // . // , . var dc = DateComponents() dc.hour = Calendar.current.component(.hour, from: date) dc.minute = Calendar.current.component(.minute, from: date) dc.second = Calendar.current.component(.second, from: date) // 10 // . , UNCalendarNotificationTrigger. let trigger = UNCalendarNotificationTrigger(dateMatching: dc, repeats: false) // 11 // , . let request = UNNotificationRequest(identifier: notificationID, content: content, trigger: trigger) // 12 // notificationCenter, . notificationCenter.add(request) { (error) in error == nil ? print(“notifacation request was added at “, trigger.nextTriggerDate()!) : print(error.debugDescription) } // 13 // . . . let action = UNNotificationAction(identifier: “showMe”, title: “Show me”, options: []) // 14 // . let category = UNNotificationCategory(identifier:userActionsIdentifier, actions: [action], intentIdentifiers: [], options: []) // 15 // notificationCenter. notificationCenter.setNotificationCategories([category]) }
func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) { … }
func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) { print(“didReceive response”) // 1 // switch switch response.actionIdentifier { case “showMe”: print(“showMe action”) // 2 // userInfo, showNotification 6, String. let mainText = response.notification.request.content.userInfo.keys.first! as! String // 3 // userInfo, showNotification 6, String. let subText = response.notification.request.content.userInfo.values.first! as! String // 4 // showNotificationlet, : // showBody true, withAction false ( ). self.showNotification(with: (mainText, subText), showBody: true, withAction: false, atDate: Date(timeInterval: 3, since: Date())) default: print(“defaul action”) } completionHandler() }
Source: https://habr.com/ru/post/451454/
All Articles