繁体   English   中英

如何使用xamarin forme pcl解决方案在iOS上运行通知?

[英]How can I get notifications to work on iOS, using xamarin forme pcl soluction?

我正在使用xamarin便携式表单开发项目。 主要重点是设置计划的通知以在iOS上运行。 我尝试了一些解决方案,例如xam.Plugins.Notifier和通知框架,但它似乎尚未出现在模拟器上。 总结一下,这是我在xamarin教程的指导下所做的事情:

iOS通知框架: https : //developer.xamarin.com/guides/ios/platform_features/introduction-to-ios10/user-notifications/enhanced-user-notifications/

AppDelegate.cs

使用用户通知;

//Request notification permissions from the user.
        UNUserNotificationCenter.Current.RequestAuthorization(UNAuthorizationOptions.Alert, (approved, err) => {
            // Handle approval
        });

便携式解决方案-MainPage.xaml.cs

使用用户通知;

        //iOS - Notification Framework (version 10 and above).
        var content = new UNMutableNotificationContent();
        content.Title = "test";
        content.Subtitle = "Notification Subtitle";
        content.Body = "test 02";
        content.Badge = 1;

        var trigger = UNTimeIntervalNotificationTrigger.CreateTrigger(5, false);

        var requestID = "123";
        var request = UNNotificationRequest.FromIdentifier(requestID, content, trigger);

        UNUserNotificationCenter.Current.AddNotificationRequest(request, (err) => {
            if (err != null)
            {
                // Do something with error...
            }
        });

我创建了一个非常简单的测试,目的只是为了触发通知,但是它似乎没有用。 任何人都对缺少的东西或其他解决方案有任何想法?

经过大量的研究和程序员自由职业者的大量帮助后,我在upwork.com上找到了,我们设法找到了解决方案。 原来我走的路是正确的,但是由于我是xamarin和C#的新手,所以我缺少了某些地方。

我们必须建立一个依赖关系使其正常工作。 我发布的代码与我的组织风格融为一体。 但是我敢肯定,任何人都可以根据自己的风格来修改此代码。

AppDelegate.cs

using Foundation;
using UIKit;
using UserNotifications; 

namespace MyApp_v1.iOS
{

[Register("AppDelegate")]
public partial class AppDelegate : global::Xamarin.Forms.Platform.iOS.FormsApplicationDelegate
{

    public override bool FinishedLaunching(UIApplication app, NSDictionary options)
    {
        //Locator.CurrentMutable.RegisterConstant(new IOSCookieStore(), typeof(IPlatformCookieStore)); //IPlatformCookieStore

        global::Xamarin.Forms.Forms.Init();





        //Notification framework.
        //----------------------
    UNUserNotificationCenter.Current.RequestAuthorization(UNAuthorizationOptions.Alert | UNAuthorizationOptions.Badge | UNAuthorizationOptions.Sound, (approved, err) => {
            // Handle approval
        });

        //Get current notification settings.
        UNUserNotificationCenter.Current.GetNotificationSettings((settings) => {
            var alertsAllowed = (settings.AlertSetting == UNNotificationSetting.Enabled);
        });
        UNUserNotificationCenter.Current.Delegate = new AppDelegates.UserNotificationCenterDelegate();
        //----------------------


        LoadApplication(new App());

        return base.FinishedLaunching(app, options);
    }


}
}

然后,我们在iOS解决方案中创建了一个委托(我将其放置在名为AppDelegates的文件夹中)。

UserNotificationCenterDelegate.cs

using System;
using System.Collections.Generic;
using System.Text;

using UserNotifications;


namespace MyApp _v1.iOS.AppDelegates
{
public class UserNotificationCenterDelegate : UNUserNotificationCenterDelegate
{
    #region Constructors
    public UserNotificationCenterDelegate()
    {
    }
    #endregion

    #region Override Methods
    public override void WillPresentNotification(UNUserNotificationCenter center, UNNotification notification, Action<UNNotificationPresentationOptions> completionHandler)
    {
        // Do something with the notification
        Console.WriteLine("Active Notification: {0}", notification);

        // Tell system to display the notification anyway or use
        // `None` to say we have handled the display locally.
        completionHandler(UNNotificationPresentationOptions.Alert);
    }
    #endregion
}
}

接下来,我们创建了对iOS解决方案的依赖关系(我将其放在名为AppDependencies的文件夹中)。

LocalNotification.cs

using System;
using UserNotifications;
using MyApp _v1.AppInterfaces;
using MyApp _v1.iOS.AppDependencies;
using Foundation;
using static CoreText.CTFontFeatureAllTypographicFeatures;

[assembly: Xamarin.Forms.Dependency(typeof(LocalNotification))]
namespace MyApp _v1.iOS.AppDependencies
{
public class LocalNotification : ILocalNotification
{


    public void ShowNotification(string strNotificationTitle, 
                                string strNotificationSubtitle, 
                                string strNotificationDescription, 
                                string strNotificationIdItem, 
                                string strDateOrInterval, 
                                int intervalType, 
                                string extraParameters)
    {
        //intervalType: 1 - set to date | 2 - set to interval


        //Object creation.
        var notificationContent = new UNMutableNotificationContent();


        //Set parameters.
        notificationContent.Title = strNotificationTitle;
        notificationContent.Subtitle = strNotificationSubtitle;
        notificationContent.Body = strNotificationDescription;
        //notificationContent.Badge = 1;
        notificationContent.Badge = Int32.Parse(strNotificationIdItem);
        notificationContent.Sound = UNNotificationSound.Default;


        //Set date.
        DateTime notificationContentDate = Convert.ToDateTime(strDateOrInterval);

        NSDateComponents notificationContentNSCDate = new NSDateComponents();
        notificationContentNSCDate.Year = notificationContentDate.Year;
        notificationContentNSCDate.Month = notificationContentDate.Month;
        notificationContentNSCDate.Day = notificationContentDate.Day;
        notificationContentNSCDate.Hour = notificationContentDate.Hour;
        notificationContentNSCDate.Minute = notificationContentDate.Minute;
        notificationContentNSCDate.Second = notificationContentDate.Second;
        notificationContentNSCDate.Nanosecond = (notificationContentDate.Millisecond * 1000000);


        //Set trigger and request.
        var notificationRequestID = strNotificationIdItem;
        UNNotificationRequest notificationRequest = null;

        if (intervalType == 1)
        {
            var notificationCalenderTrigger = UNCalendarNotificationTrigger.CreateTrigger(notificationContentNSCDate, false);

    notificationRequest = UNNotificationRequest.FromIdentifier(notificationRequestID, notificationContent, notificationCalenderTrigger);
        }
        else
        {

            var notificationIntervalTrigger = UNTimeIntervalNotificationTrigger.CreateTrigger(Int32.Parse(strDateOrInterval), false);

            notificationRequest = UNNotificationRequest.FromIdentifier(notificationRequestID, notificationContent, notificationIntervalTrigger);
        }


        //Add the notification request.
        UNUserNotificationCenter.Current.AddNotificationRequest(notificationRequest, (err) =>
        {
            if (err != null)
            {
                System.Diagnostics.Debug.WriteLine("Error : " + err);
            }
        });
    }

}
}

接下来,我们在便携式解决方案中创建了接口(我将其放置在名为AppInterfaces的文件夹中):

ILocalNotification.cs

namespace MyApp _v1.AppInterfaces
{
public interface ILocalNotification
{

    //void ShowNotification(string strTitle, string strDescription, string idNotification, string strURL);
    void ShowNotification(string strNotificationTitle, 
        string strNotificationSubtitle, 
        string strNotificationDescription, 
        string strNotificationIdItem, 
        string strDateOrInterval, 
        int intervalType, 
        string extraParameters);
}
}

最后,在便携式解决方案MainPage上,我调用创建通知的方法:

MainPage.xaml.cs

                //var notificationData = (DateTime)strNotificationDate.to;
                DateTime dateAlarmNotificationSchedule = Convert.ToDateTime(2017-28-02 08:30:00);


                //Alarm set.
                //iOS - Notification Framework (version 10 and above).
                //DependencyService.Get<ILocalNotification>().ShowNotification(strNotificationTitle, strNotificationDescription, strNotificationIdItem, strNotificationURL);
                DependencyService.Get<ILocalNotification>().ShowNotification("title example", 
                                                                            "subtitle example", 
                                                                            "description example", 
                                                                            "123", 
                                                                            strAlarmNotificationSchedule, 
                                                                            1, 
                                                                            "");

希望这对某人有帮助,因为我在网络上找不到任何地方。

看看这个插件

它说

在iOS中,您必须先请求权限才能显示本地通知,因为这是用户的干扰行为。

// Request Permissions
if (UIDevice.CurrentDevice.CheckSystemVersion(10, 0))
{
    // Request Permissions
    UNUserNotificationCenter.Current.RequestAuthorization(UNAuthorizationOptions.Alert | UNAuthorizationOptions.Badge | UNAuthorizationOptions.Sound, (granted, error) =>
    {
        // Do something if needed
    });
}
else if (UIDevice.CurrentDevice.CheckSystemVersion(8, 0))
{
    var notificationSettings = UIUserNotificationSettings.GetSettingsForTypes(
    UIUserNotificationType.Alert | UIUserNotificationType.Badge | UIUserNotificationType.Sound, null);

    app.RegisterUserNotificationSettings(notificationSettings);
}

不知道对您有没有帮助

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM