最好用UNUserNotificationCenter
.
UNUserNotificationCenter.current().delegate = self
func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
// a notification arrived while the app was in the foreground and has a value for badge, alert, or sound
// if the notification also has content-available=1 then didReceiveRemoteNotification will also be called.
// we can have iOS to display the alert normally
completionHandler([.alert, .sound, .badge])
}
func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) {
// the user took an action (i.e. tapped) on a notification
// unless you support custom notification action that run in the background the app is now in the foreground. The tap may have caused the app to launch OR brought it to the foreground OR the app may have already been in the foreground
completionHandler()
}
func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable : Any], fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) {
// a notification arrived with content-available = 1
// the application may be in the background or foreground
// note: if the app is in the foreground AND the notification also has a value for badge, alert, or sound then the userNotificationCenter(willPresent) method will also be called
completionHandler(.newData)
}