24

Я внедрил метод didReceiveRemoteNotification. Он работает и отображает контроллер вида с данными уведомления, которые передаются. Это работает только тогда, когда приложение уже было на переднем плане или было запущено в фоновом режиме. Однако, когда приложение не запущено, и пользователь нажимает уведомление, приложение запускается, но оно выглядит так, как будто уведомление не получено. Уведомление не записывается в текстовый файл, и диспетчер представлений не нажат.Вызов didReceiveRemoteNotification, когда приложение запускается в первый раз

- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo 
{ 
    if (application.applicationState == UIApplicationStateActive) 
    { 
     NSDictionary *apsInfo = [userInfo objectForKey:@"aps"]; 

     NSString *alertMsg = @""; 
     NSString *badge = @""; 
     NSString *sound = @""; 
     NSString *custom = @""; 

     if([apsInfo objectForKey:@"alert"] != NULL) 
     { 
      alertMsg = [apsInfo objectForKey:@"alert"]; 
     } 


     if([apsInfo objectForKey:@"badge"] != NULL) 
     { 
      badge = [apsInfo objectForKey:@"badge"]; 
     } 


     if([apsInfo objectForKey:@"sound"] != NULL) 
     { 
      sound = [apsInfo objectForKey:@"sound"]; 
     } 

     if([userInfo objectForKey:@"Type"] != NULL) 
     { 
      custom = [userInfo objectForKey:@"Type"]; 
     } 

     // Set your appending text. 
     NSString *textToAdd = [NSString stringWithFormat:@":%@", alertMsg]; 

     NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); 
     NSString *documentsDirectory = [paths objectAtIndex:0]; 
     NSString *fileName = [NSString stringWithFormat:@"%@/AccountNotifications.txt", documentsDirectory]; 
     NSString *fileContents = [[NSString alloc] initWithContentsOfFile:fileName usedEncoding:nil error:nil]; 

     NSString *textToFile; 

     if (fileContents == NULL) 
     { 
      textToFile = alertMsg; 
     } 

     // Here you append new text to the existing one 
     if (fileContents != NULL) 
     { 
      textToFile = [fileContents stringByAppendingString:textToAdd]; 
     } 

     // Here you save the updated text to that file 
     paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); 
     documentsDirectory = [paths objectAtIndex:0]; 
     fileName = [NSString stringWithFormat:@"%@/AccountNotifications.txt", documentsDirectory]; 
     NSString *content = textToFile; 
     [content writeToFile:fileName atomically:NO encoding:NSStringEncodingConversionAllowLossy error:nil]; 

     NSArray *fileData = [textToFile componentsSeparatedByString:@":"]; 

     NSMutableArray *tableDataFromFile; 
     tableDataFromFile = [[NSMutableArray alloc] init]; 

     int i = 0; 

     for (i = 1; i < [fileData count]; i++) 
     { 
      [tableDataFromFile addObject:fileData[i]]; 
     } 

     NotificationViewController *vc = [[NotificationViewController alloc] initWithNibName:@"NotificationViewController" bundle:nil]; 
     vc.tableData = tableDataFromFile; 

     UIViewController *root = self.mainNavController.topViewController; 
     NSArray *vcs = [NSArray arrayWithObjects:root, vc, nil]; 
     [self.mainNavController setViewControllers:vcs animated:YES]; 
    } 
     // app was already in the foreground 
    else 
    { 
     while (done == FALSE) 
     { 

     } 

     NSDictionary *apsInfo = [userInfo objectForKey:@"aps"]; 

     NSString *alertMsg = @""; 
     NSString *badge = @""; 
     NSString *sound = @""; 
     NSString *custom = @""; 

     if([apsInfo objectForKey:@"alert"] != NULL) 
     { 
      alertMsg = [apsInfo objectForKey:@"alert"]; 
     } 


     if([apsInfo objectForKey:@"badge"] != NULL) 
     { 
      badge = [apsInfo objectForKey:@"badge"]; 
     } 


     if([apsInfo objectForKey:@"sound"] != NULL) 
     { 
      sound = [apsInfo objectForKey:@"sound"]; 
     } 

     if([userInfo objectForKey:@"Type"] != NULL) 
     { 
      custom = [userInfo objectForKey:@"Type"]; 
     } 

     // Set your appending text. 
     NSString *textToAdd = [NSString stringWithFormat:@":%@", alertMsg]; 

     NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); 
     NSString *documentsDirectory = [paths objectAtIndex:0]; 
     NSString *fileName = [NSString stringWithFormat:@"%@/AccountNotifications.txt", documentsDirectory]; 
     NSString *fileContents = [[NSString alloc] initWithContentsOfFile:fileName usedEncoding:nil error:nil]; 

     NSString *textToFile; 

     if (fileContents == NULL) 
     { 
      textToFile = alertMsg; 
     } 

     // Here you append new text to the existing one 
     if (fileContents != NULL) 
     { 
      textToFile = [fileContents stringByAppendingString:textToAdd]; 
     } 

     // Here you save the updated text to that file 
     paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); 
     documentsDirectory = [paths objectAtIndex:0]; 
     fileName = [NSString stringWithFormat:@"%@/AccountNotifications.txt", documentsDirectory]; 
     NSString *content = textToFile; 
     [content writeToFile:fileName atomically:NO encoding:NSStringEncodingConversionAllowLossy error:nil]; 

     NSArray *fileData = [textToFile componentsSeparatedByString:@":"]; 

     NSMutableArray *tableDataFromFile; 
     tableDataFromFile = [[NSMutableArray alloc] init]; 

     int i = 0; 

     for (i = 1; i < [fileData count]; i++) 
     { 
      [tableDataFromFile addObject:fileData[i]]; 
     } 

     NotificationViewController *vc = [[NotificationViewController alloc] initWithNibName:@"NotificationViewController" bundle:nil]; 
     vc.tableData = tableDataFromFile; 

     UIViewController *root = self.mainNavController.topViewController; 
     NSArray *vcs = [NSArray arrayWithObjects:root, vc, nil]; 
     [self.mainNavController setViewControllers:vcs animated:YES]; 

    } 
      // app was just brought from background to foreground 


} 

Может ли кто-то помочь мне решить эту проблему? После выполнения команды doneFinishLaunchingWithOptions выполняется логическое значение true. Я просто хочу, чтобы диспетчер уведомлений открыл и отобразил уведомление, если уведомление было нажато, пока приложение не работает вообще.

ответ

33

Вы должны добавить что-то вроде этого в ваш код:

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

     NSDictionary *remoteNotif = [launchOptions objectForKey: UIApplicationLaunchOptionsRemoteNotificationKey]; 

     //Accept push notification when app is not open 
     if (remoteNotif) {  
      [self handleRemoteNotification:application userInfo:remoteNotif]; 
      return YES; 
     } 

     return YES; 
    } 

Вы можете переместить логику из didReceiveRemoteNotification в некоторой общей функции и вызвать эту функцию из обоих мест. Это будет работать, только если пользователь откроет приложение, нажав на уведомление. Если пользователь открывает приложение, нажав значок приложения, данные уведомления не будут доступны в приложении.

+0

Спасибо! Это сработало отлично. Да, было бы лучше переместить логику из didReceiveRemoteNotification в другой метод, так как это сделает код намного короче. –

+0

Добро пожаловать! – Eran

+0

@Eran Можете ли вы предоставить быстрый код? – vinbhai4u

0

Swift Code

let remoteNotif: AnyObject? = launchOptions?[UIApplicationLaunchOptionsRemoteNotificationKey] 

      //Accept push notification when app is not open 
      if ((remoteNotif) != nil) { 

       self.handleRemoteNotification(remoteNotif!) 
      } 


func handleRemoteNotification(remoteNotif: AnyObject?){ 
//handle your notification here 
} 

@Eran спасибо :)

Смежные вопросы