首次打开时,如何使我的应用程序提示“想向您发送通知”消息?

时间:2019-02-14 11:36:19

标签: xamarin xamarin.forms

我刚刚下载了一个学习应用程序(不是我的应用程序),并注意到第一次打开该应用程序时,会出现一条消息,提示您想向我发送通知。谁能解释如何编写代码以使用Forms应用程序吗?以下是显示我的意思的屏幕截图。

enter image description here

2 个答案:

答案 0 :(得分:1)

在iOS上,您需要使用UNUserNotificationCenter通过修改AppDelegate类来请求授权:

public override bool FinishedLaunching (UIApplication application, NSDictionary launchOptions)
{
    // Ask for the permission to send notifications
    UNUserNotificationCenter.Current.RequestAuthorization (UNAuthorizationOptions.Alert, (approved, err) => {
        // User approved
    });

    return true;
}

在Android上,您无需分别请求推送通知权限,并且只要设置了INTERNET权限,就无需对代码进行任何更改。

答案 1 :(得分:1)

@Timo的答案是正确的,但很少有细微的东西值得注意。

public override bool FinishedLaunching(UIApplication application, NSDictionary launchOptions)
{
    //Register your app for remote notifications.
    if (UIDevice.CurrentDevice.CheckSystemVersion(10, 0))
    {
        //iOS 10 or later
        var authOptions = UNAuthorizationOptions.Alert | UNAuthorizationOptions.Badge | UNAuthorizationOptions.Sound;
        UNUserNotificationCenter.Current.RequestAuthorization(authOptions, (granted, error) => {
            Console.WriteLine(granted);
        });

        //For iOS 10 display notification (sent via APNS)
        UNUserNotificationCenter.Current.Delegate = this;
        //Messaging.SharedInstance.Delegate = this; //FCM
    }
    else
    {
        //iOS 9 or before
        var allNotificationTypes = UIUserNotificationType.Alert | UIUserNotificationType.Badge | UIUserNotificationType.Sound;
        var settings = UIUserNotificationSettings.GetSettingsForTypes(allNotificationTypes, null);
        UIApplication.SharedApplication.RegisterUserNotificationSettings(settings);
    }
    UIApplication.SharedApplication.RegisterForRemoteNotifications();
    //App.Configure(); If using firebase
    return true;
}