Xcode 10 Swift 4.2
Pour afficher la notification push lorsque votre application est au premier plan -
Étape 1: ajoutez le délégué UNUserNotificationCenterDelegate dans la classe AppDelegate.
class AppDelegate: UIResponder, UIApplicationDelegate, UNUserNotificationCenterDelegate {
Étape 2: définir le délégué UNUserNotificationCenter
let notificationCenter = UNUserNotificationCenter.current()
notificationCenter.delegate = self
Étape 3: Cette étape permettra à votre application d'afficher la notification push même lorsque votre application est au premier plan
func userNotificationCenter(_ center: UNUserNotificationCenter,
willPresent notification: UNNotification,
withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
completionHandler([.alert, .sound])
}
Étape 4: Cette étape est facultative . Vérifiez si votre application est au premier plan et si elle est au premier plan, puis affichez Local PushNotification.
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()
}
}
Fonction de notification locale -
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)
}