我在我的应用程序中使用推送通知服务。当应用程序在后台时,我能够在通知屏幕上看到通知(当我们从iOS设备顶部向下滑动时显示的屏幕)。但如果应用程序是在前台的委托方法
- (void)application:(UIApplication*)application didReceiveRemoteNotification:(NSDictionary*)userInfo
正在被调用,但通知屏幕上没有显示通知。
我想在通知屏幕上显示通知,不管应用程序是在后台还是前台。我厌倦了寻找解决办法。任何帮助都非常感激。
iOS 14 +
下面这个答案有一个不同之处,.alert已弃用,使用.banner:
class AppDelegate: NSObject, UIApplicationDelegate, UNUserNotificationCenterDelegate {
func application(
_ application: UIApplication,
didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey : Any]? = nil
) -> Bool {
UNUserNotificationCenter.current().delegate = self
return true
}
func userNotificationCenter(
_ center: UNUserNotificationCenter,
willPresent notification: UNNotification,
withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void
) {
completionHandler([.banner, .badge, .sound])
}
}
Swift 5
1)使用UNUserNotificationCenterDelegate确认委托到AppDelegate
2)在didFinishLaunch中UNUserNotificationCenter.current().delegate = self
3)在AppDelegate中实现如下方法。
func userNotificationCenter(_ center: UNUserNotificationCenter,
willPresent notification: UNNotification,
withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
print("Push notification received in foreground.")
completionHandler([.alert, .sound, .badge])
}
就是这样!
最好的方法是通过使用扩展AppDelegate: UNUserNotificationCenterDelegate在AppDelegate中添加UNUserNotificationCenterDelegate
该扩展告诉应用程序能够在使用时获得通知
并实现这个方法
func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
completionHandler(.alert)
}
只有当应用程序在前台时,才会在委托上调用此方法。
最后的实现:
extension AppDelegate: UNUserNotificationCenterDelegate {
func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
completionHandler(.alert)
}
}
要调用这个,你必须在AppDelegate中在didFinishLaunchingWithOptions中设置委托添加这一行
UNUserNotificationCenter.current().delegate = self
你可以修改
completionHandler(.alert)
与
completionHandler([.alert, .badge, .sound]))