didReceiveRemoteNotification将用户带到正确的视图

时间:2013-11-13 04:39:14

标签: ios objective-c

我有一个聊天应用程序,我的服务器在发送新消息时发送推送通知。我遇到的问题是如何让用户看到正确的视图?我在推送通知中发送channelID,但我如何检索它并将用户带到实际的会话中?

我正在使用此代码来检测点击推送通知的时间

- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo
{
    if ( application.applicationState == UIApplicationStateInactive || application.applicationState == UIApplicationStateBackground  )
    {
         //opened from a push notification when the app was on background
    }
}

2 个答案:

答案 0 :(得分:10)

如果您在推送通知中发送channelID,则可以从userInfo字典中检索channelID。 正如中间所说 -

1) 应用程序在后台运行时当应用程序在前台运行时 application:didReceiveRemoteNotification:方法将在下面调用。

- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo
{
if ( application.applicationState == UIApplicationStateInactive)
     {
     //opened from a push notification when the app was on background

       NSString channelID = [[userInfo objectForKey:@"aps"] objectForKey:@"channelID"];
       NSLog(@"channelID->%@",channelID);
     }
  else if(application.applicationState == UIApplicationStateActive)
     {
     // a push notification when the app is running. So that you can display an alert and push in any view

       NSString channelID = [[userInfo objectForKey:@"aps"] objectForKey:@"channelID"];
       NSLog(@"channelID->%@",channelID);
     }
}

2) 当应用程序未启动(关闭)时,将调用application:didFinishedLaunchWithOptions方法。

 - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
  if (launchOptions != nil)
    {
         //opened from a push notification when the app is closed
        NSDictionary* userInfo = [launchOptions objectForKey:UIApplicationLaunchOptionsRemoteNotificationKey];
        if (userInfo != nil)
        {
            NSString channelID = [[userInfo objectForKey:@"aps"] objectForKey:@"channelID"];
            NSLog(@"channelID->%@",channelID);
        }

    }
     else{
             //opened app without a push notification.
         }
}

答案 1 :(得分:5)

您将收到有关以下情况的推送通知。

  1. 未启动应用程序时:通知中心会显示通知,应用程序徽章编号将根据通知徽章详细信息进行更新。当用户点击通知中心的通知时,您的聊天应用程序将通过调用方法 application:didFinishedLaunchWithOptions 启动通知信息。您只需要检查remoteNotification数据的选项字典。

  2. 当应用程序在前台运行时:您将收到推送通知 应用程序:didReceiveRemoteNotification:,您只需检查 userInfo 字典即可获取远程通知数据。

  3. 当应用程序在后台运行时:通知将显示在通知中心,应用程序徽章编号将根据通知徽章详细信息进行更新。当用户点击通知中心的通知时,您的聊天应用程序将进入前台,您将在应用程序:didReceiveRemoteNotification:中收到用户点击的通知,您只需要检查 userInfo 字典用于远程通知数据。

  4. 获得通知词典后,您可以访问 channelId ,并根据收到的 channelId 显示相应的聊天屏幕。

    Please refer apple doc for handling remote notifications