【问题标题】:how can my app send a push notification when my app is on the fg?当我的应用在 fg 上时,我的应用如何发送推送通知?
【发布时间】:2016-02-17 20:44:10
【问题描述】:

我有一个 swift 应用程序。

我从我的服务器收到 GCM 推送通知。

在 IOS 中,我了解操作系统会负责在我的应用位于后台时显示通知。

当我的应用在 fg 上并且我是显示通知的负责人时,我如何显示推送消息(通知)?

我应该使用本地推送(与远程推送相反)吗?

应用在后台时显示推送的代码是什么?

我知道这段代码处理向用户显示推送

但这不是通知,它只是打开一个警报

func application( application: UIApplication, didReceiveRemoteNotification userInfo: [NSObject : AnyObject], fetchCompletionHandler handler: (UIBackgroundFetchResult) -> Void) {
        print("Notification received: \(userInfo)")
        // This works only if the app started the GCM service
        GCMService.sharedInstance().appDidReceiveMessage(userInfo);
        // Handle the received message
        // Invoke the completion handler passing the appropriate UIBackgroundFetchResult value
        // [START_EXCLUDE]
        NSNotificationCenter.defaultCenter().postNotificationName(messageKey, object: nil,
            userInfo: userInfo)
        handler(UIBackgroundFetchResult.NoData);
        // [END_EXCLUDE]
}

【问题讨论】:

    标签: ios xcode swift push-notification


    【解决方案1】:

    您将收到通知(在 userInfo 中),但它不会显示应用程序是否在前台。您可以做的是在应用程序处于前台时触发本地通知或使用 UIAlertView。

    -(void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo 
    {
        application.applicationIconBadgeNumber = 0;  //For resetting the badge number to zero.           
    
    
        if (application.applicationState == UIApplicationStateActive)  //For checking if app is in foreground.        
        {                
    
           UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"Notification received:" message:[NSString stringWithFormat:@"Received notification while app was in foreground:\n%@",[[userInfo objectForKey:@"aps"] objectForKey:@"alert"]]delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil];
           [alertView show];          
      }    
    }
    

    【讨论】:

    • 你有一个快速的例子吗?
    【解决方案2】:

    如果您想在应用程序处于前台时处理通知,您可以使用像 https://github.com/LeoNatan/LNNotificationsUI 这样的自定义横幅。 代码应该是这样的:

    -(void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo 
    {
        if (application.applicationState == UIApplicationStateActive) 
        {                
            LNNotification* notification = [LNNotification notificationWithMessage:@"Notification Message"];
    
            [[LNNotificationCenter defaultCenter] presentNotification:notification forApplicationIdentifier:@"app_identifier"];
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-11-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多