Xcode 10 Swift 4.2
当您的应用程序在前台时显示推送通知 -
步骤1:在AppDelegate类中添加代理UNUserNotificationCenterDelegate。
class AppDelegate: UIResponder, UIApplicationDelegate, UNUserNotificationCenterDelegate {
第二步:设置UNUserNotificationCenter委托
let notificationCenter = UNUserNotificationCenter.current()
notificationCenter.delegate = self
步骤3: 此步骤将允许您的应用程序在前台显示推送通知。
func userNotificationCenter(_ center: UNUserNotificationCenter,
willPresent notification: UNNotification,
withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
completionHandler([.alert, .sound])
}
步骤 4:此步骤为可选。检查您的应用程序是否在前台,如果是,则显示本地推送通知。
func application(_ application: UIApplication,didReceiveRemoteNotification userInfo: [AnyHashable: Any],fetchCompletionHandler completionHandler:@escaping (UIBackgroundFetchResult) -> Void) {
let state : UIApplicationState = application.applicationState
if (state == .inactive || state == .background) {
print("background")
} else {
print("foreground")
showLocalNotification()
}
}
本地通知功能 -
fileprivate func showLocalNotification() {
let content = UNMutableNotificationContent()
content.title = "App Update"
content.body = "New version of app update is available."
content.sound = UNNotificationSound.default()
let trigger = UNTimeIntervalNotificationTrigger(timeInterval: 1, repeats: false)
let request = UNNotificationRequest(identifier: "SimplifiedIOSNotification", content: content, trigger: trigger)
notificationCenter.add(request, withCompletionHandler: nil)
}