ios - 可操作的通知不显示操作 Swift 4

标签 ios swift unusernotification

我正在学习新的通知系统,但我在执行操作时遇到了问题。通知有效,但我没有采取任何行动。我正在学习关于 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

   }
}

编辑:

@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(在:NewDate)?我认为它进入了 case waitActionIdentifier 但我什至没有将打印输出到控制台。

最佳答案

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
    // Override point for customization after application launch.
    UNUserNotificationCenter.current().delegate = self

    configureCategory()
    triggerNotification()
    requestAuth()

    return true
}


private let category = "Notification.Category.Read"

private let actionIdentifier = "Read"

private func requestAuth() {
    UNUserNotificationCenter.current().requestAuthorization(options: [.alert, .sound, .badge]) { (success, error) in
        if let error = error {
            print("Request Authorization Failed (\(error), \(error.localizedDescription))")
        }
    }
}

private func triggerNotification() {
    // Create Notification Content
    let notificationContent = UNMutableNotificationContent()

    // Configure Notification Content
    notificationContent.title = "Hello"
    notificationContent.body = "Kindly read this message."

    // Set Category Identifier
    notificationContent.categoryIdentifier = category

    // Add Trigger
    let notificationTrigger = UNTimeIntervalNotificationTrigger(timeInterval: 3.0, repeats: false)

    // Create Notification Request
    let notificationRequest = UNNotificationRequest(identifier: "test_local_notification", content: notificationContent, trigger: notificationTrigger)

    // 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: actionIdentifier, title: "Read", options: [])

    // Define Category
    let readCategory = UNNotificationCategory(identifier: category, actions: [read], 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 actionIdentifier:
        print("Read tapped")
    default:
        print("Other Action")
    }

    completionHandler()
}

enter image description here

关于ios - 可操作的通知不显示操作 Swift 4,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52128584/

相关文章:

ios - 需要有关在 iOS 中请求通知权限的说明

iphone - OpenGL ES 平铺纹理 Mipmap 问题 - iPad/iPhone

ios - SKLightNode 不使用 SKCameraNode 缩放

iphone - UIImagePickerController 不会显示相机,只有相机胶卷

swift - 带有 SwiftUI 的 VLCKit

ios - 隐蔽 3 级嵌套 json 到 Alamofire 参数

Ios 用户通知内容附件(图片)调整大小/隐藏通知扩展(长按)

ios - 在设置应用程序中看不到MyAppNotificationSettings选项

ios - 将 UIDevice identifierForVendor 存储在钥匙串(keychain)拒绝风险中

ios - 用简单的英语解释 NSIncrementalStore