OneSignal (iOS) — didReceiveNotificationRequest не вызывается

Я следовал руководству по настройке OneSignal, добавил расширение с правильным именем и получил этот файл, который они предоставили:

#import <OneSignal/OneSignal.h>

#import "NotificationService.h"

@interface NotificationService ()

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

@end

@implementation NotificationService

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


    self.receivedRequest = request;
    self.contentHandler = contentHandler;
    self.bestAttemptContent = [request.content mutableCopy];

    [OneSignal didReceiveNotificationExtensionRequest:self.receivedRequest withMutableNotificationContent:self.bestAttemptContent];

    self.contentHandler(self.bestAttemptContent);
}

- (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.

    [OneSignal serviceExtensionTimeWillExpireRequest:self.receivedRequest withMutableNotificationContent:self.bestAttemptContent];

    self.contentHandler(self.bestAttemptContent);
}
@end

Также скопировали весь свой код для AppDelegate, как указано в их руководстве по установке здесь: https://documentation.onesignal.com/docs/ios-sdk-setup плюс некоторый другой код для создания переменной «центр», как кто-то рекомендовал на github. Добавление этого экземпляра в AppDelegate сделало так, что вызывается didReceiveRemoteNotification, но не didReceiveNotificationExtensionRequest.

#import "AppDelegate.h"

@interface AppDelegate ()
#define SYSTEM_VERSION_GREATER_THAN_OR_EQUAL_TO(v)  ([[[UIDevice currentDevice] systemVersion] compare:v options:NSNumericSearch] != NSOrderedAscending)
#define SYSTEM_VERSION_LESS_THAN(v) ([[[UIDevice currentDevice] systemVersion] compare:v options:NSNumericSearch] == NSOrderedAscending)
@end

#import <OneSignal/OneSignal.h>

@implementation AppDelegate

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

    // Replace '11111111-2222-3333-4444-0123456789ab' with your OneSignal App ID.
    [OneSignal initWithLaunchOptions:launchOptions
                               appId:@"xxxxxxx (my app id is here)"
            handleNotificationAction:nil
                            settings:@{kOSSettingsKeyAutoPrompt: @false}];
    OneSignal.inFocusDisplayType = OSNotificationDisplayTypeNotification;

    // Recommend moving the below line to prompt for push after informing the user about
    //   how your app will use them.
    [OneSignal promptForPushNotificationsWithUserResponse:^(BOOL accepted) {
        NSLog(@"User accepted notifications: %d", accepted);
    }];

    UNUserNotificationCenter *center = [UNUserNotificationCenter currentNotificationCenter];
    center.delegate = self;
    // Call syncHashedEmail anywhere in your iOS app if you have the user's email.
    // This improves the effectiveness of OneSignal's "best-time" notification scheduling feature.
    // [OneSignal syncHashedEmail:userEmail];

    return YES;
}

-(void) application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo fetchCompletionHandler:(void
                                                                                                                               (^)(UIBackgroundFetchResult))completionHandler
{
    // iOS 10 will handle notifications through other methods

    if( SYSTEM_VERSION_GREATER_THAN_OR_EQUAL_TO( @"10.0" ) )
    {
        NSLog( @"iOS version >= 10. Let NotificationCenter handle this one." );
        // set a member variable to tell the new delegate that this is background

       //this block here gets called when I debug

        return;
    }
    NSLog( @"HANDLE PUSH, didReceiveRemoteNotification: %@", userInfo );

    // custom code to handle notification content

    if( [UIApplication sharedApplication].applicationState == UIApplicationStateInactive )
    {
        NSLog( @"INACTIVE" );
        completionHandler( UIBackgroundFetchResultNewData );
    }
    else if( [UIApplication sharedApplication].applicationState == UIApplicationStateBackground )
    {  
        NSLog( @"BACKGROUND" );  
        completionHandler( UIBackgroundFetchResultNewData );  
    }  
    else  
    {  
        NSLog( @"FOREGROUND" );  
        completionHandler( UIBackgroundFetchResultNewData );  
    }  
}

@end

Мне нужен didReceiveNotificationExtensionRequest, так как я пытаюсь использовать функцию изменяемого содержимого iOS 10. Я поставил точки останова и уверен, что didReceiveNotificationExtensionRequest никогда не вызывается, мне интересно, нужно ли мне подключать класс где-то еще, потому что файл .m никогда ничего не делает. Любая помощь приветствуется

Если это имеет значение, мой телефон работает под управлением iOS 10.0 (поэтому должен поддерживать изменяемый контент), а версия OneSignal — (2.5.4). Спасибо.


person Alex    schedule 23.06.2017    source источник
comment
То же самое было здесь. Пытался сделать это в Swift. Расширение не вызывалось. Как говорится на форуме OneSignal: когда для доступного содержимого установлено значение true, расширение не будет вызываться. Я отключил доступность контента, включив изменяемый контент. Я мог поймать уведомление и изменить содержимое. Структура отличается. Например: дополнительные данные можно получить как ``` let url = ((userInfo[custom] as? [String: Any])?[a] as? [String: Any])?[url] as? Строка ```   -  person Géza Mikló    schedule 27.07.2017
comment
да, та же проблема, документ oneSignal для react-native кажется неактуальным.   -  person Julien Malige    schedule 23.11.2018


Ответы (1)


В iOS 10 метод didReceiveRemoteNotification не будет вызываться... вам следует использовать

- (void)userNotificationCenter:(UNUserNotificationCenter *)center
       willPresentNotification:(UNNotification *)notification
         withCompletionHandler:(void (^)(UNNotificationPresentationOptions))completionHandler
person vivek bhoraniya    schedule 27.07.2017