Расширенное push-уведомление не работает с FCM в IOS

Я добавил UNNotificationServiceExtension и UNNotificationContentExtension в свой проект для расширенных push-уведомлений.
См. приведенный ниже код, который я добавил для того же.


Код:

#import "NotificationService.h"

@interface NotificationService ()

@property (nonatomic, strong) void (^contentHandler)(UNNotificationContent *contentToDeliver);
@property (nonatomic, strong) UNMutableNotificationContent *bestAttemptContent;

@end

@implementation NotificationService {
    NSURLSession *session;
}

- (void)didReceiveNotificationRequest:(UNNotificationRequest *)request withContentHandler:(void (^)(UNNotificationContent * _Nonnull))contentHandler {

    self.contentHandler = contentHandler;
    self.bestAttemptContent = [request.content mutableCopy];
    NSDictionary *userInfo = request.content.userInfo;
    if (userInfo == nil) {
        [self contentComplete];
        return;
    }

    if ([userInfo objectForKey:@"pic_url"]) {
        [self loadAttachmentForUrlString:[userInfo objectForKey:@"pic_url"]
                       completionHandler: ^(UNNotificationAttachment *attachment) {
                           self.bestAttemptContent.attachments = [NSArray arrayWithObjects:attachment, nil];
                       }];
    }
}

- (void)loadAttachmentForUrlString:(NSString *)urlString
                 completionHandler:(void (^)(UNNotificationAttachment *))completionHandler
{
    __block UNNotificationAttachment *attachment = nil;
    __block NSURL *attachmentURL = [NSURL URLWithString:urlString];

    NSString *fileExt = [@"." stringByAppendingString:[urlString pathExtension]];


    session = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];

    NSURLSessionDownloadTask *task = [session downloadTaskWithURL:attachmentURL
                                                completionHandler: ^(NSURL *temporaryFileLocation, NSURLResponse *response, NSError *error) {
                                                    if (error != nil)
                                                    {
                                                        NSLog(@"%@", error.localizedDescription);
                                                    }
                                                    else
                                                    {
                                                        NSFileManager *fileManager = [NSFileManager defaultManager];
                                                        NSURL *localURL = [NSURL fileURLWithPath:[temporaryFileLocation.path
                                                                                                  stringByAppendingString:fileExt]];
                                                        [fileManager moveItemAtURL:temporaryFileLocation
                                                                             toURL:localURL
                                                                             error:&error];

                                                        NSError *attachmentError = nil;
                                                        attachment = [UNNotificationAttachment attachmentWithIdentifier:[attachmentURL lastPathComponent]
                                                                                                                    URL:localURL
                                                                                                                options:nil
                                                                                                                  error:&attachmentError];
                                                        if (attachmentError)
                                                        {
                                                            NSLog(@"%@", attachmentError.localizedDescription);
                                                        }
                                                    }
                                                    completionHandler(attachment);
                                                }];

    [task resume];
}

- (void)serviceExtensionTimeWillExpire {
    // Called just before the extension will be terminated by the system.
    // Use this as an opportunity to deliver your "best attempt" at modified content, otherwise the original push payload will be used.
    [self contentComplete];
}

- (void)contentComplete
{
    [session invalidateAndCancel];
    self.contentHandler(self.bestAttemptContent);
}

@end

Я использую следующую полезную нагрузку

    {
   "to": "9yJUWBA",
   "mutable_content": true,
   "category": "myNotificationCategory",
   "notification":
   {                                               
      "title":"Realtime Custom Push Notifications",
       "subtitle":"Now with iOS 10 support!",
       "body":"Add multimedia content to your notifications"
   }
}

Проблема в том, что я не получаю уведомления. Я использовал следующий учебник для реализации расширенного push-уведомления. Я проверил разные доступные ответы, но ни один из них не сработал для меня. Я также пытался отладить метод didReceiveNotificationRequest, подключив процесс расширения, но точка останова не сработала.

http://Link


comment
вы проверите полезную нагрузку, если некоторые ключи отсутствуют, например, aps, Alert и т. д....   -  person chirag shah    schedule 20.07.2018
comment
Попробуйте это решение stackoverflow.com/a/50523908/5084797.   -  person manishsharma93    schedule 27.07.2018


Ответы (1)


-(void)userNotificationCenter:(UNUserNotificationCenter *)center willPresentNotification:(UNNotification *)notification withCompletionHandler:(void (^)(UNNotificationPresentationOptions options))completionHandler{

    //Called when a notification is delivered to a foreground app.
    NSLog(@"Userinfo willPresentNotification%@",notification.request.content.userInfo);

    // Print message ID.
    /*
     NSDictionary *userInfo = notification.request.content.userInfo;
     if (userInfo[kGCMMessageIDKey]) {
     NSLog(@"Message ID: %@", userInfo[kGCMMessageIDKey]);
     }
     */


    completionHandler(UNNotificationPresentationOptionAlert);

}

-(void)userNotificationCenter:(UNUserNotificationCenter *)center didReceiveNotificationResponse:(UNNotificationResponse *)response withCompletionHandler:(void(^)())completionHandler{

    //Called to let your app know which action was selected by the user for a given notification.
    NSLog(@"Userinfo didReceiveNotificationResponse%@",response.notification.request.content.userInfo);

    // Print message ID.
    /*
     NSDictionary *userInfo = notification.request.content.userInfo;
     if (userInfo[kGCMMessageIDKey]) {
     NSLog(@"Message ID: %@", userInfo[kGCMMessageIDKey]);
     }
     */


}

Используйте вышеуказанные методы, и этот метод доступен для iOS 10 и более поздних версий. для расширения службы уведомлений об отладке перейдите по ссылке ниже

Расширения уведомлений об отладке

если вы оказываете поддержку своему приложению iOS 9 и выше, вы должны указать оба метода ниже для выше iOS 10, и вы также написали в своем вопросе

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

    // If you are receiving a notification message while your app is in the background,
    // this callback will not be fired till the user taps on the notification launching the application.
    // TODO: Handle data of notification

    // With swizzling disabled you must let Messaging know about the message, for Analytics
    // [[FIRMessaging messaging] appDidReceiveMessage:userInfo];
    /*
     // Print message ID.
     if (userInfo[kGCMMessageIDKey]) {
     NSLog(@"Message ID: %@", userInfo[kGCMMessageIDKey]);
     }
     */
    // Print full message.
    NSLog(@"Userinfo didReceiveRemoteNotification 1 %@",userInfo);


}

- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo fetchCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler {
    // If you are receiving a notification message while your app is in the background,
    // this callback will not be fired till the user taps on the notification launching the application.
    // TODO: Handle data of notification

    // With swizzling disabled you must let Messaging know about the message, for Analytics
    // [[FIRMessaging messaging] appDidReceiveMessage:userInfo];

    /*
     // Print message ID.
     if (userInfo[kGCMMessageIDKey]) {
     NSLog(@"Message ID: %@", userInfo[kGCMMessageIDKey]);
     }
     */
    // Print full message.

    NSLog(@"Userinfo didReceiveRemoteNotification 2 %@",userInfo);


    completionHandler(UIBackgroundFetchResultNewData);
}

дайте мне знать, если у вас есть запрос.

person Ankur Patel    schedule 20.07.2018