单击应用程序时加载推送通知数据

Jar*_*ich 4 iphone ipad ios

我通过推送通知实现了我的iPhone应用程序.我基本上成功实现了推送通知.当我点击推送通知消息时,该消息将显示在ViewController上的消息标签上.但是,当我打开图标(应用程序)时,它没有返回任何通知.我需要显示推送通知,不仅要点击推送通知,而且如果iOS用户也只是打开应用程序,它应该有效.

这是我的代码.

AppDelegate.m

 -(BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary  
 *)launchOptions
  {

      [[UIApplication sharedApplication] registerForRemoteNotificationTypes:
       (UIRemoteNotificationTypeBadge | UIRemoteNotificationTypeSound | UIRemoteNotificationTypeAlert)];

  }



- (void)application:(UIApplication*)application didReceiveRemoteNotification: (NSDictionary*)userInfo{

     NSString *messageAlert = [[userInfo objectForKey:@"aps"] objectForKey:@"alert"];
     NSLog(@"Received Push Message: %@", messageAlert );

     [[NSNotificationCenter defaultCenter] postNotificationName:@"MyNotification"   object:messageAlert];
Run Code Online (Sandbox Code Playgroud)

在我的ViewController.m上

- (void)viewDidLoad
{

    [super viewDidLoad];

    [[NSNotificationCenter defaultCenter] addObserverForName:@"MyNotification" object:nil queue:nil usingBlock:^(NSNotification *note) {
    NSString *_string = note.object;

    messages.text = _string; //message

}];
}
}
Run Code Online (Sandbox Code Playgroud)

它会在我点击通知时显示通知.但是当我打开应用程序时,通知也必须显示该消息.怎么做?请帮我.

Arp*_*tha 9

推送通知主要有四种状态进入设备.让我们逐一考虑每个案例: -

情况1:当应用程序真正未加载到内存中时(例如,当您启动它时,启动屏幕会显示等),然后调用application:didFinishLaunchingWithOptions,您可以按如下方式获取推送通知:

 NSDictionary *remoteNotif = [launchOptions objectForKey:UIApplicationLaunchOptionsRemoteNotificationKey];

 if(remoteNotif)
 {
   //Handle remote notification
 }
Run Code Online (Sandbox Code Playgroud)

情况2:如果应用程序加载到内存中并且处于活动状态(例如,应用程序当前在设备上打开),则仅应用程序:(UIApplication*)app didReceiveRemoteNotification :( NSDictionary*)userInfo被调用.正常的,正如你在这种情况下说的那样成功.

情况3:如果应用程序已加载到内存但不是ACTIVE并且没有后台(例如,您启动了应用程序,然后按下主页按钮,等待10秒),然后单击推送通知上的操作按钮,仅调用didReceiveRemoteNotification.按照以下方法.

-(void)application:(UIApplication *)app didReceiveRemoteNotification:(NSDictionary *)userInfo
{
    if([app applicationState] == UIApplicationStateInactive)
    {
         //If the application state was inactive, this means the user pressed an action   button
         // from a notification. 

         //Handle notification
    }
}
Run Code Online (Sandbox Code Playgroud)

情况4:当应用程序在后台然后点击图标时,根据Apple的文档,您无法检索所有待处理的通知.

注意:为了解决这个问题,Apple在iOS 7中引入了应用程序后台启动的概念.但到目前为止,你不能这样做,直到iOS 6开发你必须坚持下去.

希望这有助于你!