Xcode 10 斯威夫特 4.2
当您的应用程序处于前台时显示推送通知 -
第 1 步:在 AppDelegate 类中添加委托 UNUserNotificationCenterDelegate。
class AppDelegate: UIResponder, UIApplicationDelegate, UNUserNotificationCenterDelegate {
第 2 步:设置 UNUserNotificationCenter 委托
let notificationCenter = UNUserNotificationCenter.current()
notificationCenter.delegate = self
第 3 步:此步骤将允许您的应用程序显示推送通知,即使您的应用程序在前台也是如此
func userNotificationCenter(_ center: UNUserNotificationCenter,
willPresent notification: UNNotification,
withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
completionHandler([.alert, .sound])
}
第四步:这一步是可选的。检查您的应用程序是否在前台,如果它在前台,则显示 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()
}
}
本地通知功能 -
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)
}