C# 当应用程序未关闭时,Xamarin.iOS处理推送通知

C# 当应用程序未关闭时,Xamarin.iOS处理推送通知,c#,push-notification,xamarin.ios,C#,Push Notification,Xamarin.ios,如果应用程序在后台,我使用didReceiveMemotentification方法处理推送通知。如果应用程序位于前台且未关闭,是否有办法处理推送通知?谢谢您实施了吗?如果您在iOS 10+上部署项目,您可以尝试在FinishedLaunching(UIApplication应用程序,NSDictionary launchOptions)中订阅通知,如: if (UIDevice.CurrentDevice.CheckSystemVersion(10, 0)) { var authOpt

如果应用程序在后台,我使用didReceiveMemotentification方法处理推送通知。如果应用程序位于前台且未关闭,是否有办法处理推送通知?谢谢

您实施了吗?如果您在iOS 10+上部署项目,您可以尝试在
FinishedLaunching(UIApplication应用程序,NSDictionary launchOptions)
中订阅通知,如:

if (UIDevice.CurrentDevice.CheckSystemVersion(10, 0))
{
    var authOptions = UNAuthorizationOptions.Alert | UNAuthorizationOptions.Badge | UNAuthorizationOptions.Sound;
    UNUserNotificationCenter.Current.RequestAuthorization(authOptions, (granted, error) => {
        Console.WriteLine(granted);
    });
    UNUserNotificationCenter.Current.Delegate = new MyNotificationCenterDelegate();
}
然后,当通知到达且应用程序位于前台时,
WillPresentNotification()
将触发,此句柄事件返回通知到达时应用程序将响应的操作。最后,您可以在
DidReceiveNotificationResponse()
事件中获取用户信息:

public class MyNotificationCenterDelegate : UNUserNotificationCenterDelegate
{
    public override void DidReceiveNotificationResponse(UNUserNotificationCenter center, UNNotificationResponse response, Action completionHandler)
    {
        completionHandler();
    }

    public override void WillPresentNotification(UNUserNotificationCenter center, UNNotification notification, Action<UNNotificationPresentationOptions> completionHandler)
    {
        completionHandler(UNNotificationPresentationOptions.Sound | UNNotificationPresentationOptions.Alert);

    }       
}
公共类MyNotificationCenterDelegate:UnuseNotificationCenterDelegate
{
公共覆盖无效DidReceiveNotificationResponse(UNUserNotificationCenter、UNNotificationResponse、Action completionHandler)
{
completionHandler();
}
public override void WillPresentNotification(未使用通知中心、未通知通知通知、操作完成处理程序)
{
completionHandler(UNNotificationPresentationOptions.Sound | UNNotificationPresentationOptions.Alert);
}       
}

但是,如果您不想实现
UserNotification
,或者只需使用键
content available
true来推送静默远程通知,
didReceiveRemoteNotification()即使应用程序位于前台,也会被激发。

当您在前台收到推送通知时,将激发
AppDelegate
中的覆盖方法
ReceivedRemoteNotification
DidReceiveRemoteNotification

在该方法中,您可以检查应用程序是否处于
活动状态
,并根据该状态处理通知

if (UIApplication.SharedApplication.ApplicationState == UIApplicationState.Active) 
{
    //You app is in Foreground state.
    //Process the Pushnotification data, or show alert.
}

实施 应用程序(:DidReceiveEmotentification:fetchCompletionHandler:) 方法,而不是尽可能使用此方法。如果你的代表 实现这两种方法,应用程序对象调用 应用程序(:DidReceiveEmotentification:fetchCompletionHandler:) 方法


因此,如果您在AppDelegate中实现了两种方法(
ReceivedRemoteNotification
&
DidReceiveMemoteNotification
),则将调用
DidReceiveMemoteNotification
方法来处理推送通知事件,而不管应用程序在前台还是后台运行。按照以下步骤获取DidReceivereMotenofication将始终被调用

1) 重写AppDelegate.cs中的DidReceiveMemoteNotification方法

public override void DidReceiveRemoteNotification(UIApplication application, NSDictionary userInfo, Action<UIBackgroundFetchResult> completionHandler)

}

通过下面显示的示例app.delegte.cs代码,我在Xamarin iOS中获得了前台和后台通知

   using Foundation;
   using System;
   using System.Diagnostics;
   using System.Linq;
   using UIKit;
   using UserNotifications;
   using WindowsAzure.Messaging;
   using Firebase.Core;
   using Firebase.CloudMessaging;
   using System.Runtime.CompilerServices;
   using ObjCRuntime;

   namespace NotificationHubSample.iOS
{ [注册(“AppDelegate”)]

public分部类AppDelegate:global::Xamarin.Forms.Platform.iOS.FormsApplicationDelegate
{
专用SBNotificationHub集线器{get;set;}
公共覆盖bool FinishedLaunching(UIApplication应用程序、NSDictionary选项)
{
全局::Xamarin.Forms.Forms.Init();
加载应用程序(新应用程序());
基础。完成发射(应用程序,选项);
Firebase.Core.App.Configure();
注册表项的详细说明();
UIApplication.SharedApplication.SetMinimumBackgroundFetchInterval(UIApplication.BackgroundFetchIntervalMinimum);
返回true;
}
无效登记处更改通知()
{
//根据系统版本注册远程通知
if(UIDevice.CurrentDevice.CheckSystemVersion(10,0))
{
UNUserNotificationCenter.Current.RequestAuthorization(UNAuthorizationOptions.Alert|
未授权选项。声音|
未授权选项。声音,
(已批准,错误)=>
{
如果(授予)
InvokeOnMainThread(UIApplication.SharedApplication.RegisterForRemotonifications);
});
}
else if(UIDevice.CurrentDevice.CheckSystemVersion(8,0))
{
var pushSettings=UIUserNotificationSettings.GetSettingsForTypes(
UIUserNotificationType.Alert | UIUserNotificationType.Badge | UIUserNotificationType.Sound,
新NSSet());
UIApplication.SharedApplication.RegisterUserNotificationSettings(推送设置);
UIApplication.SharedApplication.RegisterForRemotonifications();
}
其他的
{
UIRemoteNotificationType notificationTypes=UIRemoteNotificationType.Alert | UIRemoteNotificationType.Badge | UIRemoteNotificationType.Sound;
UIApplication.SharedApplication.RegisterForRemoteNotificationTypes(notificationTypes);
}
UIApplication.SharedApplication.RegisterForRemotonifications();
}
公共覆盖无效注册更正(UIApplication应用程序,NSData deviceToken)
{
Hub=新的SBNotificationHub(AppConstants.ListenConnectionString,AppConstants.NotificationHubName);
//更新Azure通知中心的注册
Hub.UnregisterAll(deviceToken,(错误)=>
{
if(错误!=null)
{
Debug.WriteLine($“无法调用注销{error}”);
返回;
}
var tags=newnsset(AppConstants.SubscriptionTags.ToArray());
Hub.RegisterNative(deviceToken,标记,(errorCallback)=>
{
if(errorCallback!=null)
{
WriteLine($“RegisterNativeAsync错误:{errorCallback}”);
}
});
var templateExpiration=DateTime.Now.AddDays(120).ToString(System.Globalization.CultureInfo.CreateSpecificCulture(“en-US”);
中心
   using Foundation;
   using System;
   using System.Diagnostics;
   using System.Linq;
   using UIKit;
   using UserNotifications;
   using WindowsAzure.Messaging;
   using Firebase.Core;
   using Firebase.CloudMessaging;
   using System.Runtime.CompilerServices;
   using ObjCRuntime;

   namespace NotificationHubSample.iOS
   public partial class AppDelegate : global::Xamarin.Forms.Platform.iOS.FormsApplicationDelegate
{
    private SBNotificationHub Hub { get; set; }
    

    public override bool FinishedLaunching(UIApplication app, NSDictionary options)
    {
        global::Xamarin.Forms.Forms.Init();
        LoadApplication(new App());

        

        base.FinishedLaunching(app, options);

        Firebase.Core.App.Configure();

        RegisterForRemoteNotifications();

        UIApplication.SharedApplication.SetMinimumBackgroundFetchInterval(UIApplication.BackgroundFetchIntervalMinimum);


        return true;
    }

    void RegisterForRemoteNotifications()
    {
        // register for remote notifications based on system version
        if (UIDevice.CurrentDevice.CheckSystemVersion(10, 0))
        {
            
            

            UNUserNotificationCenter.Current.RequestAuthorization(UNAuthorizationOptions.Alert |
                UNAuthorizationOptions.Sound |
                UNAuthorizationOptions.Sound,
                (granted, error) =>
                {
                    if (granted)
                        InvokeOnMainThread(UIApplication.SharedApplication.RegisterForRemoteNotifications);
                });
        }
        else if (UIDevice.CurrentDevice.CheckSystemVersion(8, 0))
        {
            var pushSettings = UIUserNotificationSettings.GetSettingsForTypes(
            UIUserNotificationType.Alert | UIUserNotificationType.Badge | UIUserNotificationType.Sound,
            new NSSet());

            UIApplication.SharedApplication.RegisterUserNotificationSettings(pushSettings);
            UIApplication.SharedApplication.RegisterForRemoteNotifications();
        }
        else
        {
            UIRemoteNotificationType notificationTypes = UIRemoteNotificationType.Alert | UIRemoteNotificationType.Badge | UIRemoteNotificationType.Sound;
            UIApplication.SharedApplication.RegisterForRemoteNotificationTypes(notificationTypes);
        }
        UIApplication.SharedApplication.RegisterForRemoteNotifications();
    }

    public override void RegisteredForRemoteNotifications(UIApplication application, NSData deviceToken)
    {
        Hub = new SBNotificationHub(AppConstants.ListenConnectionString, AppConstants.NotificationHubName);

        // update registration with Azure Notification Hub
        Hub.UnregisterAll(deviceToken, (error) =>
        {
            if (error != null)
            {
                Debug.WriteLine($"Unable to call unregister {error}");
                return;
            }

            var tags = new NSSet(AppConstants.SubscriptionTags.ToArray());
            Hub.RegisterNative(deviceToken, tags, (errorCallback) =>
            {
                if (errorCallback != null)
                {
                    Debug.WriteLine($"RegisterNativeAsync error: {errorCallback}");
                }
            });

            var templateExpiration = DateTime.Now.AddDays(120).ToString(System.Globalization.CultureInfo.CreateSpecificCulture("en-US"));
            Hub.RegisterTemplate(deviceToken, "defaultTemplate", AppConstants.APNTemplateBody, templateExpiration, tags, (errorCallback) =>
            {
                if (errorCallback != null)
                {
                    if (errorCallback != null)
                    {
                        Debug.WriteLine($"RegisterTemplateAsync error: {errorCallback}");
                    }
                }
            });
        });

        // Firebase ios Registration
        Messaging.SharedInstance.ApnsToken = deviceToken;
        
       }
   // Process the notification when the app is open.
   
public override void ReceivedRemoteNotification(UIApplication application, NSDictionary userInfo)
    {
        ProcessNotification(userInfo, false);
        

    }   // End of the ReceiveRemoteNotification method

    

    // Process the notification when the app is closed.
    public override void DidReceiveRemoteNotification(UIApplication application, NSDictionary userInfo, Action<UIBackgroundFetchResult> completionHandler)
    {
        ProcessNotification(userInfo, false);            
        
    }


    void ProcessNotification(NSDictionary options, bool fromFinishedLaunching)
    {
        // make sure we have a payload
        if (options != null && options.ContainsKey(new NSString("aps")))
        {
            // get the APS dictionary and extract message payload. Message JSON will be converted
            // into a NSDictionary so more complex payloads may require more processing
            NSDictionary aps = options.ObjectForKey(new NSString("aps")) as NSDictionary;
            
            string payload = string.Empty;
            NSString payloadKey = new NSString("alert");
            
            if (aps.ContainsKey(payloadKey))
            {
                payload = aps[payloadKey].ToString();
            }

          
            
            if (!string.IsNullOrWhiteSpace(payload))
            {
                (App.Current.MainPage as MainPage)?.AddMessage(payload);
            }

        }
        else
        {
            Debug.WriteLine($"Received request to process notification but there was no payload.");
        } 
     } // End of the ProcessNotification method





}