App 在前台时获取本地通知 Swift 4 iOS 11

Get local notification when App is in foreground Swift 4 iOS 11

我想在我的应用程序处于前台时收到本地通知,当我尝试使用以下代码时它从未触发通知,但当我在后台进入应用程序时它确实触发了。

这是我尝试过的:

//Schedule a Local Notification
func ScheduleNotification(timeInterval: Double, repeats: Bool, notificationBody:String, title:String){

    let trigger = UNTimeIntervalNotificationTrigger.init(timeInterval: timeInterval, repeats: repeats)

    let center = UNUserNotificationCenter.current()

    let identifier = "UYLLocalNotification"
    let content = UNMutableNotificationContent()
    content.title = title
    content.body = notificationBody
    content.sound = UNNotificationSound.default()
    let request = UNNotificationRequest(identifier: identifier, content: content, trigger: trigger)
    center.add(request, withCompletionHandler: { (error) in
        if let error = error {
            //Something went wrong
            print(error.localizedDescription)
        }
    })
}

override func viewDidLoad() {
    super.viewDidLoad()

    if Currentcount < data.count {
        self.ScheduleNotification(timeInterval: 5.0, repeats: false, notificationBody: "You have \(data.count - Currentcount) notification", title: "Alert!")
    }
}

如有任何帮助,我们将不胜感激 谢谢

当您的应用程序处于前台时,通知也可能会触发。

默认情况下,当通知到达且目标应用程序位于前台时,iOS 不会显示任何 UI。显示通知内容是应用程序的工作。使用 UNUserNotificationCenterDelegate 您可以非常轻松地将通知显示为警报。有关详细信息,请参阅

这里我一步步给大家展示UNUserNotificationCenterDelegate是如何工作的

  1. 在 AppDelegate 中:import UserNotifications

  2. class AppDelegate: UIResponder,UNUserNotificationCenterDelegate{}

  3. didFinishLaunchingWithOptions

    中将委托方法分配给 self
    func application(_application:UIApplication,
    didFinishLaunchingWithOptionslaunchoptions:[UIApplicationLaunchOptionsKey: Any]?) -> Bool {
    
           UIApplication.shared.applicationIconBadgeNumber = 0
                let center = UNUserNotificationCenter.current()
                center.delegate = self        
                center.requestAuthorization(options:[.badge, .alert, .sound]) { (granted, error) in
    
                    if granted {
                        DispatchQueue.main.async { // Correct
                            UIApplication.shared.registerForRemoteNotifications()
                        }
    
                    }
    
                }
    
        }
    
  4. 您希望在本地通知中显示的内容

         func assignValueToNotification
            {
                let content = UNMutableNotificationContent()
                content.body = "Asssign body"
                content.userInfo = ["identifier": "info"]
                content.sound = UNNotificationSound.default()
                content.badge = UIApplication.shared.applicationIconBadgeNumber + 1 as NSNumber;
                content.categoryIdentifier = "write category identifier"
                // Deliver the notification in five seconds.
                let trigger = UNTimeIntervalNotificationTrigger.init(timeInterval: 0.5, repeats: false)
                let request = UNNotificationRequest.init(identifier: region.identifier as String, content: content, trigger: trigger)
               // Schedule the notification.
               let center = UNUserNotificationCenter.current()
               center.add(request)
        }
    
  5. 写下您的委托方法,当您单击本地通知时将调用该方法。

    func userNotificationCenter(_ center:UNUserNotificationCenter, didReceive response:UNNotificationResponse,withCompletionHandler completionHandler: @escaping () -> Void{
        print("Received Local Notification:")
    }
    

您只需将 UNUserNotificationCenterDelegatewillPresent 委托函数添加到您的 AppDelegate

只需将 .sound, .banner UNNotificationPresentationOptions 放入完成处理程序,您的本地通知就会在您的应用程序位于前台时显示。

extension AppDelegate: UNUserNotificationCenterDelegate {
    
    func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
        completionHandler([.sound, .banner])
    }
}

还有一步:你当然需要在 didFinishLaunchingWithOptions.

中设置 UNUserNotificationCenter 委托
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey : Any]? = nil) -> Bool {  
    UNUserNotificationCenter.current().delegate = self
}

备注

对于 SwiftUI Cycles,您可以像这样访问 AppDelegate: