我想让用户仅在我们提示“ AskNotification”视图时和单击“是”时才允许通知。
为此,我做了以下工作:
public static AppDelegate Self { get; private set; }
public override bool FinishedLaunching(UIApplication app, NSDictionary options)
{
HtmlLabelRenderer.Initialize();
global::Xamarin.Forms.Forms.Init();
// Notifications
Firebase.Core.App.Configure();
//AllowNotifications();
...
LoadApplication(new App());
AppDelegate.Self = this;
return base.FinishedLaunching(app, options);
}
public void AllowNotifications()
{
//In iOS you must request permission to show local / remote notifications first since it is a user interrupting action.
if (UIDevice.CurrentDevice.CheckSystemVersion(10, 0))
{
// Request Permissions
UNUserNotificationCenter.Current.RequestAuthorization(
UNAuthorizationOptions.Alert | UNAuthorizationOptions.Badge | UNAuthorizationOptions.Sound,
(granted, error) =>
{
// Do something if needed
});
// For iOS 10 display notification (sent via APNS)
UNUserNotificationCenter.Current.Delegate = this;
// For iOS 10 data message (sent via FCM)
Messaging.SharedInstance.Delegate = this;
}
else
{
// iOS 9 or before
var allNotificationTypes = UIUserNotificationType.Alert
| UIUserNotificationType.Badge
| UIUserNotificationType.Sound;
var settings = UIUserNotificationSettings
.GetSettingsForTypes(allNotificationTypes, null);
UIApplication.SharedApplication.RegisterUserNotificationSettings(settings);
}
Messaging.SharedInstance.ShouldEstablishDirectChannel = true;
Console.WriteLine("-------- RegisterForRemoteNotifications");
UIApplication.SharedApplication.RegisterForRemoteNotifications();
}
然后在用户单击“允许”按钮(从我的角度来看)的“我的代码隐藏”中,执行以下操作:
AppDelegate appDelegate = AppDelegate.Self;
appDelegate.AllowNotifications();
如您所见,我正在使用Singleton模式来访问AppDelegate。我的问题是,在AppDelegate内部调用“ AllowNotifications”(在上面的代码中有注释)时,系统提示询问用户并收到通知。
但是当我从另一个页面使用Singleton模式调用AllowNotification方法时。系统弹出窗口显示,我们用户单击“是”,它允许在iOS参数上进行通知。但是我从来没有进入过我的“ DidReceiveMessage”方法。
感谢您的帮助
答案 0 :(得分:1)
此问题与您的代码无关。这是预期的行为。因为您使用的是Firebase(来自NuGet的Xamarin.Firebase.iOS.CloudMessaging
)。
对于运行iOS 10及更高版本的设备,必须在应用程序启动完成之前,将委托对象分配给UNUserNotificationCenter对象以接收显示通知,将FIRMessaging对象分配给数据消息。例如,在iOS应用中,必须使用方法FinishedLaunching
进行分配。
也就是说,当您通过方法FinishedLaunching
注册通知时,即使显示系统弹出窗口,该注册仍将不起作用。
有关更多详细信息,请参阅here。