从AppDelegate中的另一个类访问UNUserNotificationCenterDelegate

时间:2019-08-04 12:08:59

标签: swift class appdelegate unusernotificationcenter

在我的应用中,您可以为每个清单设置提醒。本地通知在名为Checklist的类中设置。我在通知中添加了操作,当应用程序在后台运行时可以正常工作,但是在关闭应用程序时则什么也没有发生。我发现下面的代码似乎可以满足我的要求。我想在我的课堂上保持通知的实际安排。我的问题是我的班级包含init和Codable,但我不知道如何从AppDelegate调用它。当我执行与此处代码完全相同的操作时,会收到该错误:

  

不能为没有参数的“检查表”类型调用初始化器

有人知道如何解决这个问题吗?

class UYLNotificationDelegate: NSObject, UNUserNotificationCenterDelegate {
      func userNotificationCenter(_ center: UNUserNotificationCenter,
           willPresent notification: UNNotification, 
          withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
        // Play sound and show alert to the user
        completionHandler([.alert,.sound])
      }

      func userNotificationCenter(_ center: UNUserNotificationCenter,
           didReceive response: UNNotificationResponse,
           withCompletionHandler completionHandler: @escaping () -> Void) {
        switch response.actionIdentifier {
        case UNNotificationDismissActionIdentifier:
          print("Dismiss Action")
        case UNNotificationDefaultActionIdentifier:
          print("Default")
        case "Snooze":
          print("Snooze")
        case "Delete":
          print("Delete")  
        default:
          print("Unknown action")
        }
        completionHandler()
      }
    }

在AppDelegate中:

    let notificationDelegate = UYLNotificationDelegate()

    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {

      let center = UNUserNotificationCenter.current()
      center.delegate = notificationDelegate

      // ...
      return true
    }`

0 个答案:

没有答案