如何使用单一实例在没有应用程序委托的情况下设置本地通知



听到我对这个本地通知有更多的疑问

  • 如何在没有appdelegate的情况下设置本地通知?
  • 如何使用单独的控制器呼叫代表?

这是我的代码!!

import Foundation
import UserNotifications
class NotificationController {
  private static var privateShared: NotificationController?
  static var shared: NotificationController {
    if privateShared == nil {
      privateShared = NotificationController()
    }
    return privateShared!
  }
  class func destroy() {
    privateShared = nil
  }
  private let notificationCenter = UNUserNotificationCenter.current()
  func registerLocalNotification(controller: UIViewController){
    notificationCenter.delegate = self
    let options: UNAuthorizationOptions = [.alert, .sound, .badge]
    notificationCenter.requestAuthorization(options: options) {
      (didAllow, error) in
      if !didAllow {
        print("User has declined notifications")
      }
    }
  }
}

通知类的扩展:

extension NotificationController: UNUserNotificationCenterDelegate {
  func userNotificationCenter(_ center: UNUserNotificationCenter,
                              willPresent notification: UNNotification,
                              withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
    completionHandler([.alert, .sound])
  }
  func userNotificationCenter(_ center: UNUserNotificationCenter,
                              didReceive response: UNNotificationResponse,
                              withCompletionHandler completionHandler: @escaping () -> Void) {
    if response.notification.request.identifier == "Local Notification" {
      print("Handling notifications with the Local Notification Identifier")
    }
    completionHandler()
  }
  func scheduleNotification(notificationType: String) {
    let content = UNMutableNotificationContent() // Содержимое уведомления
    let categoryIdentifire = "Delete Notification Type"
    content.title = notificationType
    content.body = "This is example how to create " + notificationType
    content.sound = UNNotificationSound.default
    content.badge = 1
    content.categoryIdentifier = categoryIdentifire
    let trigger = UNTimeIntervalNotificationTrigger(timeInterval: 5, repeats: false)
    let identifier = "Local Notification"
    let request = UNNotificationRequest(identifier: identifier, content: content, trigger: trigger)
    notificationCenter.add(request) { (error) in
      if let error = error {
        print("Error (error.localizedDescription)")
      }
    }
    let snoozeAction = UNNotificationAction(identifier: "Snooze", title: "Snooze", options: [])
    let deleteAction = UNNotificationAction(identifier: "DeleteAction", title: "Delete", options: [.destructive])
    let category = UNNotificationCategory(identifier: categoryIdentifire,
                                          actions: [snoozeAction, deleteAction],
                                          intentIdentifiers: [],
                                          options: [])
    notificationCenter.setNotificationCategories([category])
  }
}

如果没有应用程序委派,我无法配置本地通知

有什么东西想念我吗?

任何参考欣赏!!

谢谢。

只是在iOS上处理通知的入门,并遇到了同样的问题。这是我在单例实例中使用用户通知的实现。

import Foundation
import UserNotifications
class NotificationControl {
        static let shared = NotificationControl()
        private let notificationCenter = UNUserNotificationCenter.current()
        func requestAuthorization() {
            notificationCenter.requestAuthorization(options: [.alert, .badge, .sound, .criticalAlert, .provisional]) { (granted, error) in
                guard granted else { return }
                print(granted)
                self.getNotificationSettings()
            }
        }
        func getNotificationSettings() {
            notificationCenter.getNotificationSettings { (settings) in
                print(settings)
            }
        }
        func scheduleNotification(notificationType:String) {
            let content = UNMutableNotificationContent()
            content.title = notificationType
            content.body = "Notification example"
            content.sound = UNNotificationSound.defaultCritical
            content.badge = 1
            let trigger = UNTimeIntervalNotificationTrigger(timeInterval: 3, repeats: false)
            let identifier = "Local Notification"
            let request = UNNotificationRequest(identifier: identifier, content: content, trigger: trigger)
            notificationCenter.add(request) { (error) in
                guard let error = error else { return }
                print(error.localizedDescription)
            }
        }
    }

应用代表:

import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
    var window: UIWindow?
    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
        NotificationControl.shared.requestAuthorization()
        return true
    }
    func applicationDidBecomeActive(_ application: UIApplication) {
        UIApplication.shared.applicationIconBadgeNumber = 0
    }
}

相关内容

最新更新