Xcode 10 Swift 4.2
Para mostrar notificaciones push cuando su aplicación está en primer plano:
Paso 1: agregue delegado UNUserNotificationCenterDelegate en la clase AppDelegate.
class AppDelegate: UIResponder, UIApplicationDelegate, UNUserNotificationCenterDelegate {
Paso 2: configurar el delegado UNUserNotificationCenter
let notificationCenter = UNUserNotificationCenter.current()
notificationCenter.delegate = self
Paso 3: este paso permitirá que su aplicación muestre notificaciones push incluso cuando su aplicación esté en primer plano
func userNotificationCenter(_ center: UNUserNotificationCenter,
willPresent notification: UNNotification,
withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
completionHandler([.alert, .sound])
}
Paso 4: este paso es opcional . Compruebe si su aplicación está en primer plano y si está en primer plano, luego muestre Notificación local de inserción.
func application(_ application: UIApplication,didReceiveRemoteNotification userInfo: [AnyHashable: Any],fetchCompletionHandler completionHandler:@escaping (UIBackgroundFetchResult) -> Void) {
let state : UIApplicationState = application.applicationState
if (state == .inactive || state == .background) {
// go to screen relevant to Notification content
print("background")
} else {
// App is in UIApplicationStateActive (running in foreground)
print("foreground")
showLocalNotification()
}
}
Función de notificación local
fileprivate func showLocalNotification() {
//creating the notification content
let content = UNMutableNotificationContent()
//adding title, subtitle, body and badge
content.title = "App Update"
//content.subtitle = "local notification"
content.body = "New version of app update is available."
//content.badge = 1
content.sound = UNNotificationSound.default()
//getting the notification trigger
//it will be called after 5 seconds
let trigger = UNTimeIntervalNotificationTrigger(timeInterval: 1, repeats: false)
//getting the notification request
let request = UNNotificationRequest(identifier: "SimplifiedIOSNotification", content: content, trigger: trigger)
//adding the notification to notification center
notificationCenter.add(request, withCompletionHandler: nil)
}