Я изучаю новую систему уведомлений, но у меня возникают проблемы с действиями. Уведомление работает, но я не получаю действия с ним. Я следую учебному пособию по https://www.appcoda.com/ios10-user-notifications-guide/, но, похоже, действия не отображаются с уведомлением.
Как вы можете видеть закомментированную часть в func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey : Any]? = nil)
, где я не могу понять, куда она идет, может кто-нибудь увидеть, где я ошибаюсь?
import UIKit
import UserNotifications
@UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func scheduleNotification(at date: Date) {
UNUserNotificationCenter.current().delegate = self
//compone a new Date components because components directly from Date don't work
let calendar = Calendar(identifier: .gregorian)
let components = calendar.dateComponents(in: .current, from: date)
let newComponents = DateComponents(calendar: calendar, timeZone: .current, month: components.month, day: components.day, hour: components.hour, minute: components.minute)
//create the trigger with above new date components, with no repetitions
let trigger = UNCalendarNotificationTrigger(dateMatching: newComponents, repeats: false)
//create the content for the notification
let content = UNMutableNotificationContent()
content.title = "Tutorial Reminder"
content.body = "Just a reminder to read your tutorial over at appcoda.com!"
content.sound = UNNotificationSound.default()
// notification action category
//add an image to notification
//convert logo to url
if let path = Bundle.main.path(forResource: "logo", ofType: "png") {
let url = URL(fileURLWithPath: path)
do { // because UNNotificationAttachment is mark as throwing we need an attach block for handling errors
let attachment = try UNNotificationAttachment(identifier: "logo", url: url, options: nil)
content.attachments = [attachment]
content.categoryIdentifier = "myCategory"
} catch {
print("The attachment was not loaded.")
}
}
//create the request for notification with desired parameters
let request = UNNotificationRequest(identifier: "textNotification", content: content, trigger: trigger)
//add the request to notification center after removing all notifications
UNUserNotificationCenter.current().removeAllPendingNotificationRequests()
UNUserNotificationCenter.current().add(request) {(error) in
if let error = error {
print("Uh oh! We had an error: \(error)")
}
}
}
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey : Any]? = nil) -> Bool {
// let action = UNNotificationAction(identifier: "remindLater", title: "Remind me later", options: [])
// let category = UNNotificationCategory(identifier: "myCategory", actions: [action], intentIdentifiers: [], options: [])
// UNUserNotificationCenter.current().setNotificationCategories([category])
UNUserNotificationCenter.current().requestAuthorization(options: [.alert, .sound]) {(accepted, error) in
if !accepted {
// print("Notification access denied.")
// let action = UNNotificationAction(identifier: "remindLater", title: "Remind me later", options: [])
// let category = UNNotificationCategory(identifier: "myCategory", actions: [action], intentIdentifiers: [], options: [])
// UNUserNotificationCenter.current().setNotificationCategories([category])
}
}
let action = UNNotificationAction(identifier: "remindLater", title: "Remind me later", options: [])
let category = UNNotificationCategory(identifier: "myCategory", actions: [action], intentIdentifiers: [], options: [])
UNUserNotificationCenter.current().setNotificationCategories([category])
return true
}
}
extension AppDelegate: UNUserNotificationCenterDelegate {
func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) {
if response.actionIdentifier == "remindLater" {
let newDate = Date(timeInterval: 5, since: Date())
scheduleNotification(at: newDate)
}
// UNUserNotificationCenter.current().delegate = self
}
}
EDIT:
после ответа @ VIP-DEV я изменил код, чтобы добавить напоминание в собственном действии, на:
import UIKit
import UserNotifications
@UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
UNUserNotificationCenter.current().delegate = self as? UNUserNotificationCenterDelegate
configureCategory()
triggerNotification(at: Date())
requestAuth()
return true
}
private let category = "Notification.Category.Read"
private let readActionIdentifier = "Read"
private let waitActionIdentifier = "Wait"
private func requestAuth() {
UNUserNotificationCenter.current().requestAuthorization(options: [.alert, .sound, .badge]) { (success, error) in
if let error = error {
print("Request Authorization Failed (\(error), \(error.localizedDescription))")
}
}
}
func triggerNotification(at date: Date) {
// Create Notification Content
let notificationContent = UNMutableNotificationContent()
//compone a new Date components because components directly from Date don't work
let calendar = Calendar(identifier: .gregorian)
let components = calendar.dateComponents(in: .current, from: date)
let newComponents = DateComponents(calendar: calendar, timeZone: .current, month: components.month, day: components.day, hour: components.hour, minute: components.minute)
//create the trigger with above new date components, with no repetitions
// Configure Notification Content
notificationContent.title = "Hello"
notificationContent.body = "Kindly read this message."
// Set Category Identifier
notificationContent.categoryIdentifier = category
// Add Trigger
// let notificationTrigger = UNTimeIntervalNotificationTrigger(timeInterval: 10.0, repeats: false)
let trigger = UNCalendarNotificationTrigger(dateMatching: newComponents, repeats: false)
// // Create Notification Request
let notificationRequest = UNNotificationRequest(identifier: "test_local_notification", content: notificationContent, trigger: trigger)
//
// Add Request to User Notification Center
UNUserNotificationCenter.current().add(notificationRequest) { (error) in
if let error = error {
print("Unable to Add Notification Request (\(error), \(error.localizedDescription))")
}
}
}
private func configureCategory() {
// Define Actions
let read = UNNotificationAction(identifier: readActionIdentifier, title: "Read", options: [])
let wait = UNNotificationAction(identifier: waitActionIdentifier, title : "Wait", options: [])
// Define Category
let readCategory = UNNotificationCategory(identifier: category, actions: [read, wait], intentIdentifiers: [], options: [])
// Register Category
UNUserNotificationCenter.current().setNotificationCategories([readCategory])
}
func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
completionHandler([.alert])
}
func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) {
switch response.actionIdentifier {
case readActionIdentifier:
print("Read tapped")
case waitActionIdentifier:
let NewDate = Date(timeInterval: 20, since: Date())
triggerNotification(at: NewDate)
print("Wait tapped")
default:
print("Other Action")
}
completionHandler()
}
}
и
class ViewController: UIViewController {
@IBAction func datePickerDidSelectNewDate(_ sender: UIDatePicker) {
let selectedDate = sender.date
let delegate = UIApplication.shared.delegate as? AppDelegate
// delegate?.scheduleNotification(at: selectedDate)
delegate?.triggerNotification(at: selectedDate)
}
}
Теперь я не могу установить новое уведомление при нажатии на кнопку ожидания. где я должен установить let NewDate = Date(timeInterval: 20, since: Date())
triggerNotification(at: NewDate)
? Я думал, что это вошло в case waitActionIdentifier
, но я даже не получаю печать на консоль.