【问题标题】:OneSignal Not calling didReceiveRemoteNotificationOneSignal 未调用 didReceiveRemoteNotification
【发布时间】:2017-03-28 18:18:32
【问题描述】:

我们从 UA 迁移到 One Signal。我们正在从云代码发送推送,例如

var pushInfo = {
      "app_id" : "xxxxxx",          
      "data": {
          "objectId": objectId,
          "placeId": placeId,
      },
      "included_segments": ["All Users"],
      "contents": {"en": message}
};
var headers = {
    "Content-Type": "application/json; charset=utf-8",
    "Authorization": "Basic XXXXX"
};

var options = {
 host: "onesignal.com",
 port: 443,
 path: "/api/v1/notifications",
 method: "POST",
 headers: headers,
};

var https = require('https');
var req = https.request(options, function(res) {  
res.on('data', function(data) {
  console.log("Response:");
  console.log(JSON.parse(data));
});
});

req.on('error', function(e) {
console.log("ERROR:");
console.log(e);
 });  
req.write(JSON.stringify(pushInfo));
req.end();

在我的 AppDelegate.m 中

[OneSignal initWithLaunchOptions:launchOptions appId:@"XXXXX"];

现在早些时候,当收到通知并且用户点击它时,它曾经调用过

-(void) application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo fetchCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler

问。现在没有调用它。如何使用 OneSignal 处理它。 问:我需要做些什么来处理无声通知(没有可见的徽章/横幅等)

【问题讨论】:

    标签: ios push-notification apple-push-notifications onesignal


    【解决方案1】:

    我假设您正在 iOS10 设备上测试/运行您的应用,

    我查看了 OneSignal SDK 代码,我认为当设备上检测到 iOS10 时,SDK 会自动使用新的 UserNotifications 框架(在 iOS10 中添加)。

    在这种情况下,您上面提到的AppDelegate方法不会被调用,而是UNUserNotificationCenterDelegate中的方法被调用,这些方法被SDK捕获以记录点击/查看。

    要解决此问题,请创建一个实现 OSUserNotificationCenterDelegate 的新类,并使用 [OneSignal setNotificationCenterDelegate:yourCustomNotificationCenterDelegateInstance] 将其实例提供给 OneSignal

    请注意,当静默推送通知(内容可用:1)到达时,application:didReceiveRemoteNotification:fetchCompletionHandler: 仍会被调用,但如果使用了UNUserNotificationCenterDelegate,则当用户点击通知时不会调用它。

    此外,iOS 10.0.X 上存在一个问题,其中调用了 application:didReceiveRemoteNotification 而不是 application:didReceiveRemoteNotification:fetchCompletionHandler: 请参阅:https://forums.developer.apple.com/thread/54332,但我怀疑您是否属于这种情况。

    【讨论】:

    • 谢谢。只使用 [OneSignal initWithLaunchOptions:launchOptions appId:@"XXXX" handleNotificationReceived:^(OSNotification *notification) { } 可能是一个好主意,这将始终在 iOS8/9/10
    【解决方案2】:

    单信号通知集成

    使用以下代码块来处理 PushNotification 消息内容

    将以下代码放入AppDelegate 的 ApplicationDidFinishLaunch 选项方法

        let notificationReceivedBlock: OSHandleNotificationReceivedBlock = { notification in
    
            print("Received Notification: \(notification!.payload.notificationID)")
        }
    
        let notificationOpenedBlock: OSHandleNotificationActionBlock = { result in
            // This block gets called when the user reacts to a notification received
            let payload: OSNotificationPayload = result!.notification.payload
    
            var fullMessage = payload.body
            print("Message = \(String(describing: fullMessage))")
    
            if payload.additionalData != nil {
                if payload.title != nil {
                    let messageTitle = payload.title
                    print("payload.category \(payload.category)")
                    print("payload.subtitle \(payload.subtitle)")
                    print("Message Title = \(messageTitle!)")
                }
    
                let additionalData = payload.additionalData
                if additionalData?["actionSelected"] != nil {
                    fullMessage = fullMessage! + "\nPressed ButtonID: \(String(describing: additionalData!["actionSelected"]))"
                }
            }
        }
    
        let onesignalInitSettings = [kOSSettingsKeyAutoPrompt: false,
                                     kOSSettingsKeyInAppLaunchURL: true]
    
        OneSignal.initWithLaunchOptions(launchOptions,
                                        appId: "Your App Id",
                                        handleNotificationReceived: notificationReceivedBlock,
                                        handleNotificationAction: notificationOpenedBlock,
                                        settings: onesignalInitSettings)
       **Use following block of code To Receive OneSingnal Notification Content** 
    
        OneSignal.inFocusDisplayType = OSNotificationDisplayType.notification;
    
        // Recommend moving the below line to prompt for push after informing the user about
        //   how your app will use them.
        OneSignal.promptForPushNotifications(userResponse: { accepted in
            print("User accepted notifications: \(accepted)")
        })
    

    【讨论】:

      【解决方案3】:

      application:didReceiveRemoteNotification:fetchCompletionHandler: 是后台静音content-available 通知的正确选择器。确保您使用的是 latest 2.2.2 OneSignal SDK,因为有一些修复程序可以保持与旧 AppDelegate 选择器的兼容性。

      您可能需要考虑在 iOS 10 设备上使用 UNNotificationServiceExtensionmutable-content,因为当应用程序被刷掉时这仍然有效。

      【讨论】:

        【解决方案4】:

        就我而言,我所要做的就是删除应用委托中的 Firebase 处理程序。 OneSignal 可以从 FCM 劫持事件。这样我就有了 OneSingal 推送通知和 Firebase 提供的通知。至于 One 信号,我使用了他们示例中的简单复制和粘贴。

        这是我从 AppDelegate.m 中删除的部分

        REMOVE IMPORTS -> #import "RNFirebaseMessaging.h"
        REMOVE IMPORTS -> #import "RNFirebaseNotifications.h"
        
        IN: - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
        REMOVE ->[RNFirebaseNotifications configure];
        
        REMOVE HANDLERS:
        - (void)application:(UIApplication *)application 
        didReceiveLocalNotification:(UILocalNotification *)notification {
          [[RNFirebaseNotifications instance] 
        didReceiveLocalNotification:notification];
        }
        - (void)application:(UIApplication *)application 
        didReceiveRemoteNotification:(nonnull NSDictionary *)userInfo
                                                           
        fetchCompletionHandler:(nonnull void (^). 
        (UIBackgroundFetchResult))completionHandler{
          [[RNFirebaseNotifications instance] 
        didReceiveRemoteNotification:userInfo 
        fetchCompletionHandler:completionHandler];
          [UIApplication sharedApplication].applicationIconBadgeNumber += 1;
        }
        
        - (void)application:(UIApplication *)application 
        didRegisterUserNotificationSettings:(UIUserNotificationSettings 
        *)notificationSettings {
          [[RNFirebaseMessaging instance] 
        didRegisterUserNotificationSettings:notificationSettings];
        }
        

        import { Platform } from 'react-native'
        import OneSignal, { NotificationReceivedEvent, OpenedEvent } from 'react-native-onesignal'
        import Config from '../../Config/Config'
        import State from '../../State/State'
        
        interface WithSuccess {
            success: boolean
        }
        
        interface ExternalUserIdResultI {
            push: WithSuccess
            email: WithSuccess
            sms: WithSuccess
        }
        
        class Messaging {
        
            public Init = () => {
                //OneSignal Init Code
                OneSignal.setLogLevel(Config.messaging.debugLevel, 0)
                OneSignal.setAppId(Platform.OS === 'ios' ? Config.messaging.iosAppId : Config.messaging.androidAppId)
                //END OneSignal Init Code
        
                //Prompt for push on iOS
                OneSignal.promptForPushNotificationsWithUserResponse((response: boolean) => {
                    console.log("Prompt response:", response);
                })
        
                //Method for handling notifications received while app in foreground
                OneSignal.setNotificationWillShowInForegroundHandler((notificationReceivedEvent: NotificationReceivedEvent) => {
                    console.log("OneSignal: notification will show in foreground:", notificationReceivedEvent);
                    let notification = notificationReceivedEvent.getNotification();
                    console.log("notification: ", notification);
                    notificationReceivedEvent.complete(notification)
                })
        
                //Method for handling notifications opened
                OneSignal.setNotificationOpenedHandler((notification: OpenedEvent) => {
                    console.log("OneSignal: notification opened:", notification);
                })
        
                OneSignal.addSubscriptionObserver(event => {
                    console.log("OneSignal: subscription changed:", event);
                })
            }
        
            public SendTag = (key: string, value: string) => {
                OneSignal.sendTag(key, value)
            }
        
            public SetExternalUserId = (externalUserId: string) => {
                //@ts-ignore
                OneSignal.setExternalUserId(externalUserId, (results: ExternalUserIdResultI) => {
                    // The results will contain push and email success statuses
                    console.log('Results of setting external user id');
                    console.log(results);
                    
                    // Push can be expected in almost every situation with a success status, but
                    // as a pre-caution its good to verify it exists
                    if (results.push && results.push.success) {
                      console.log('Results of setting external user id push status:');
                      console.log(results.push.success);
                    }
                    
                    // Verify the email is set or check that the results have an email success status
                    if (results.email && results.email.success) {
                      console.log('Results of setting external user id email status:');
                      console.log(results.email.success);
                    }
                  
                    // Verify the number is set or check that the results have an sms success status
                    if (results.sms && results.sms.success) {
                      console.log('Results of setting external user id sms status:');
                      console.log(results.sms.success);
                    }
                  });
            }
        
            public RemoveExternalUserId = () => {
                //@ts-ignore
                OneSignal.removeExternalUserId((results: ExternalUserIdResultI) => {
                    // The results will contain push and email success statuses
                    console.log('Results of removing external user id');
                    console.log(results);
                    // Push can be expected in almost every situation with a success status, but
                    // as a pre-caution its good to verify it exists
                    if (results.push && results.push.success) {
                      console.log('Results of removing external user id push status:');
                      console.log(results.push.success);
                    }
                    
                    // Verify the email is set or check that the results have an email success status
                    if (results.email && results.email.success) {
                      console.log('Results of removoing external user id email status:');
                      console.log(results.email.success);
                    }
                  });
            }
        
        }
        
        export default new Messaging()

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2020-06-30
          • 1970-01-01
          • 2023-03-25
          • 1970-01-01
          • 1970-01-01
          • 2015-11-14
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多