在前台iOS中的App时获取推送通知

Ab'*_*tio 171 iphone objective-c push-notification ios

我在我的应用程序中使用推送通知服务.当应用程序在后台时,我能够在通知屏幕上看到通知(当我们从iOS设备的顶部向下滑动时显示的屏幕).但是如果应用程序在前台是委托方法

- (void)application:(UIApplication*)application didReceiveRemoteNotification:(NSDictionary*)userInfo
Run Code Online (Sandbox Code Playgroud)

正在调用,但通知屏幕中不显示通知.

我想在通知屏幕上显示通知,无论应用程序是在后台还是前台.我厌倦了寻找解决方案.任何帮助是极大的赞赏.

che*_*sam 172

要在应用程序位于前台时显示横幅消息,请使用以下方法.

iOS 10,Swift 3/4:

// This method will be called when app received push notifications in foreground
func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) 
{
    completionHandler([.alert, .badge, .sound])
}
Run Code Online (Sandbox Code Playgroud)

iOS 10,Swift 2.3:

@available(iOS 10.0, *)
func userNotificationCenter(center: UNUserNotificationCenter, willPresentNotification notification: UNNotification, withCompletionHandler completionHandler: (UNNotificationPresentationOptions) -> Void)
{
    //Handle the notification
    completionHandler(
       [UNNotificationPresentationOptions.Alert,
        UNNotificationPresentationOptions.Sound,
        UNNotificationPresentationOptions.Badge])
}
Run Code Online (Sandbox Code Playgroud)

您还必须将您的应用代表注册为通知中心的代表:

import UserNotifications

// snip!

class AppDelegate : UIResponder, UIApplicationDelegate, UNUserNotificationCenterDelegate

// snip!

   func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {

      // set the delegate in didFinishLaunchingWithOptions
      UNUserNotificationCenter.current().delegate = self
      ...
   }
Run Code Online (Sandbox Code Playgroud)

  • 不要忘记将Notification Center委托设置为app delegate:应用程序中的`UNUserNotificationsCenter.current().delegate = self` didFinishLaunchingWithOptions (21认同)
  • 对于仍在挣扎的人来说,UNUserNotificationCenter不是UNUserNotificationsCenter,而是以's'为中心 (2认同)

Mah*_*eri 56

下面的代码将适合您:

- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo  {
    application.applicationIconBadgeNumber = 0;             
    //self.textView.text = [userInfo description];
    // We can determine whether an application is launched as a result of the user tapping the action
    // button or whether the notification was delivered to the already-running application by examining
    // the application state.

    if (application.applicationState == UIApplicationStateActive) {                
        // Nothing to do if applicationState is Inactive, the iOS already displayed an alert view.                
        UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"Did receive a Remote Notification" message:[NSString stringWithFormat:@"Your App name received this notification while it was running:\n%@",[[userInfo objectForKey:@"aps"] objectForKey:@"alert"]]delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil];
        [alertView show];          
    }    
}
Run Code Online (Sandbox Code Playgroud)


Avi*_*oss 38

对于任何可能感兴趣的人,我最终创建了一个自定义视图,看起来像顶部的系统推送横幅,但添加了一个关闭按钮(小蓝色X)和一个选项来点击消息进行自定义操作.它还支持在用户有时间读取/解除旧通知之前到达多个通知的情况(没有限制可以堆积多少...)

链接到GitHub:AGPushNote

用法基本上是在线:

[AGPushNoteView showWithNotificationMessage:@"John Doe sent you a message!"];
Run Code Online (Sandbox Code Playgroud)

它在iOS7上看起来像这样(iOS6具有iOS6的外观和感觉......)

在此输入图像描述


Ash*_*ale 31

目标C.

在此输入图像描述

因为iOS 10我们需要集成willPresentNotification显示通知横幅的方法foreground.

如果app处于前台模式(活动)

- (void)userNotificationCenter:(UNUserNotificationCenter* )center willPresentNotification:(UNNotification* )notification withCompletionHandler:(void (^)(UNNotificationPresentationOptions options))completionHandler {
    NSLog( @“Here handle push notification in foreground" ); 
    //For notification Banner - when app in foreground

    completionHandler(UNNotificationPresentationOptionAlert);

    // Print Notification info
    NSLog(@"Userinfo %@",notification.request.content.userInfo);
}
Run Code Online (Sandbox Code Playgroud)


Ab'*_*tio 23

如果应用程序在前台运行,iOS将不会显示通知横幅/警报.这是设计的.但我们可以通过UILocalNotification如下使用来实现它

  • 在收到远程
    通知时检查应用程序是否处于活动状态.如果处于活动状态,则触发UILocalNotification.

    if (application.applicationState == UIApplicationStateActive ) {
    
        UILocalNotification *localNotification = [[UILocalNotification alloc] init];
        localNotification.userInfo = userInfo;
        localNotification.soundName = UILocalNotificationDefaultSoundName;
        localNotification.alertBody = message;
        localNotification.fireDate = [NSDate date];
        [[UIApplication sharedApplication] scheduleLocalNotification:localNotification];
    }
    
    Run Code Online (Sandbox Code Playgroud)

迅速:

if application.applicationState == .active {
    var localNotification = UILocalNotification()
    localNotification.userInfo = userInfo
    localNotification.soundName = UILocalNotificationDefaultSoundName
    localNotification.alertBody = message
    localNotification.fireDate = Date()
    UIApplication.shared.scheduleLocalNotification(localNotification)
}
Run Code Online (Sandbox Code Playgroud)

  • 我不认为这会有所帮助.本地和远程通知的处理方式相同,因此当本地通知触发时,如果应用程序正在运行,则不会显示/播放徽章/横幅或声音. (85认同)
  • 这实际上不起作用.来自UILocalNotification文档:`如果应用程序在系统发送通知时最重要且可见,则调用应用程序委托的应用程序:didReceiveLocalNotification:来处理通知.使用提供的UILocalNotification对象中的信息来确定要采取的操作.当应用程序已经位于最前端时,系统不会显示任何警报,标记应用程序的图标或播放任何声音 (18认同)
  • 它还会在iOS通知中心留下一个条目 (3认同)
  • 但是,当推送通知到来时,我不会启动本地通知.我会发起类似的行为,就像提到的@ Rick77:显示警报或一些烤面包机.我想我不必再通过操作系统来处理操作系统要求我处理的事情. (3认同)
  • 此解决方案正在运行,因为本地和远程处理方式相同,当应用程序处于前台时,在远程通知到来时创建位置通知将不会显示任何内容.使用警报或自定义警报是解决方案 (3认同)

小智 14

对于 Swift 5

1) 确认委托给 AppDelegate UNUserNotificationCenterDelegate

2)UNUserNotificationCenter.current().delegate = selfdidFinishLaunch

3) 在AppDelegate.

func userNotificationCenter(_ center: UNUserNotificationCenter,
                                willPresent notification: UNNotification,
                                withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
     print("Push notification received in foreground.")
     completionHandler([.alert, .sound, .badge])
}
Run Code Online (Sandbox Code Playgroud)

就是这样!


Dan*_*tín 13

如果应用程序在前台运行,iOS将不会显示通知横幅/警报.这是设计的.您必须编写一些代码来处理应用程序在前台接收通知时的情况.您应该以最合适的方式显示通知(例如,将徽章编号添加到UITabBar图标,模拟通知中心横幅等).

  • 请记住,这个答案是真的**仅适用于iOS 9及更低版本**.从iOS 10开始,Apple推出了一个新的API来处理通知(`UNUserNotificationCenter`API).除了新的API,现在**可以在应用程序位于前台时显示通知.**因此,如果您因为这个问题中的答案不同而感到困惑,那是因为有些答案太旧了,并且仅描述iOS 9及之前的行为,而其他的则没有考虑到`UNUserNotificationCenter`仅在iOS 10中可用. (7认同)
  • @ Ab'initio我不确定,但在iOS中所有应用程序都不是平等的.我想股票邮件应用程序正在使用公共SDK中没有的某种私有API.或者,通知代码可能是Apple的Mail app id异常. (3认同)

mar*_*101 9

您可以创建自己的模仿横幅提醒的通知.

一种方法是创建一个看起来像横幅的自定义uiview,可以设置动画并响应触摸.考虑到这一点,您可以使用更多功能创建更好的横幅.

或者你可以找一个为你做的api,并将它们作为podfiles添加到你的项目中.

这是我用过的一对夫妇:

https://github.com/terryworona/TWMessageBarManager

https://github.com/toursprung/TSMessages


SPa*_*tel 9

根据Apple 文档,是的,您可以在应用程序运行时显示通知在此输入图像描述


Kav*_*gam 8

以下是app处于活动状态(前台或打开)时接收推送通知的代码. UNUserNotificationCenter文档

@available(iOS 10.0, *)
func userNotificationCenter(center: UNUserNotificationCenter, willPresentNotification notification: UNNotification, withCompletionHandler completionHandler: (UNNotificationPresentationOptions) -> Void)
{
     completionHandler([UNNotificationPresentationOptions.Alert,UNNotificationPresentationOptions.Sound,UNNotificationPresentationOptions.Badge])
}
Run Code Online (Sandbox Code Playgroud)

如果您需要访问userInfo的通知使用代码: notification.request.content.userInfo


Pra*_*wad 6

Xcode 10 Swift 4.2

要在您的应用程序位于前台时显示推送通知-

步骤1:在AppDelegate类中添加委托UNUserNotificationCenterDelegate。

class AppDelegate: UIResponder, UIApplicationDelegate, UNUserNotificationCenterDelegate {
Run Code Online (Sandbox Code Playgroud)

步骤2:设置UNUserNotificationCenter委托

let notificationCenter = UNUserNotificationCenter.current()
notificationCenter.delegate = self
Run Code Online (Sandbox Code Playgroud)

步骤3:即使您的应用程序位于前台,此步骤也将允许您的应用程序显示“推送通知”

func userNotificationCenter(_ center: UNUserNotificationCenter,
                                willPresent notification: UNNotification,
                                withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
        completionHandler([.alert, .sound])

    }
Run Code Online (Sandbox Code Playgroud)

步骤4:此步骤是可选的。检查您的应用程序是否在前台,以及是否在前台,然后显示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()
        }
    }
Run Code Online (Sandbox Code Playgroud)

本地通知功能-

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)
    }
Run Code Online (Sandbox Code Playgroud)

  • 这是一个很好的例子,说明需要读取某个线程的所有回复。前面的线程提到了该方法,而不是委托,最后这是您需要执行的所有三个步骤。谢谢普拉尚特的完整回答! (2认同)