Xamarin iOS - 推送通知 - 区分点击已到达的推送通知

时间:2016-04-03 10:03:44

标签: ios xamarin push-notification xamarin.ios apple-push-notifications

我正在创建一个包含推送通知的Xamarin.iOS应用程序。

我注意到如果应用程序没有运行(不仅仅是在后台),当推送通知到达时(使用正确的有效负载),操作系统将接管处理通知并将其呈现给用户并且如果用户在关闭时点击通知,我将能够从FinishedLaunching方法的NSDictionary选项参数中获取此信息(查找它是否包含UIApplication.LaunchOptionsRemoteNotificationKey键)

到目前为止,一切都很棒。

但我有两个场景,

1)推送通知在应用程序运行时到达。 2)用户在启动应用程序后点击了之前到达的推送通知(应用程序已关闭)

对于这两种情况,都会调用ReceivedRemoteNotification方法。

但是对于每个场景我想做一个不同的业务逻辑,我的问题是: 我如何知道方案1或方案2是否调用了ReceivedRemoteNotification?

我是Xamarin的新手,我在网上搜索过它,但找不到解决方案。

任何人都可以帮我这个吗?

感谢。

3 个答案:

答案 0 :(得分:4)

使用以下条件检查应用程序状态,在didReceiveRemoteNotification方法中,

UIApplicationState state = [[UIApplication sharedApplication] applicationState];
if (state == UIApplicationStateBackground || state == UIApplicationStateInactive)
{//write here...Application opened by tapping notification}

仅供参考 - 以上代码在Objective-c

答案 1 :(得分:3)

我认为,当应用程序启动时,通过用户点击应用程序停止时收到的通知,我已经看到ReceivedRemoteNotification已调用isAppAlreadyRunning。在设备上发送通知时,如果应用程序正在运行,我才会看到此调用。因此,如果从false调用FinishedLaunching true,则ReceivedRemoteNotification调用AppDelegate.cs。{/ 1}}

这似乎在运费Xamarin.iOS应用程序中运行良好。所有代码都在public override bool FinishedLaunching(UIApplication app, NSDictionary options) { ... // Initialize Xamarin Forms and load the application. Xamarin.Forms.Forms.Init(); LoadApplication(new Forms.App(0)); // Check if App was opened by Push Notification. var keyName = new NSString("UIApplicationLaunchOptionsRemoteNotificationKey"); if (options != null && options.Keys != null && options.Keys.Length != 0 && options.ContainsKey(keyName)) { NSDictionary pushOptions = options.ObjectForKey(keyName) as NSDictionary; ProcessPushNotification(pushOptions, false); } return base.FinishedLaunching(app, options); } public override void ReceivedRemoteNotification(UIApplication app, NSDictionary userInfo) { Debug.WriteLine("ReceivedRemoteNotification entered."); ProcessPushNotification(userInfo, true); } protected void ProcessPushNotification(NSDictionary userInfo, bool isAppAlreadyRunning) { if (userInfo == null) return; if (isAppAlreadyRunning) { // do something with this knowledge... } ... }

.populate('surveyResponseId')

答案 2 :(得分:2)

非常感谢@RJVKumar这就是我要找的东西!

为了帮助其他人,这是C#中的代码:

public override void ReceivedRemoteNotification(UIApplication application, NSDictionary userInfo)
{
    if (application.ApplicationState == UIApplicationState.Active)
    {
    }
    else if (application.ApplicationState == UIApplicationState.Background)
    {
    }
    else if (application.ApplicationState == UIApplicationState.Inactive)
    {
    }
}