c# - 如何使用 xamarin forms pcl 解决方案获取在 iOS 上工作的通知?

标签 c# ios asp.net mobile xamarin

我正在开发一个项目,使用 xamarin forms portable。主要重点是设置预定通知以在 iOS 上运行。我尝试了一些解决方案,如 xam.Plugins.Notifier 和通知框架,但它似乎还没有出现在模拟器上。总结一下,这是我按照 xamarin 教程上的指南所做的:

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

AppDelegate.cs

using UserNotifications;

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

可移植解决方案 - MainPage.xaml.cs

using UserNotifications;

        //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 解决方案中创建了一个委托(delegate)(我放在一个名为 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, 
                                                                            "");

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

关于c# - 如何使用 xamarin forms pcl 解决方案获取在 iOS 上工作的通知?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42661197/

相关文章:

iphone - 检测 iPhone 音量按钮向上按下?

javascript - Facebook 搜索 API 不受信任的连接

c# - Devexpress ASPxGridView GetSelectedFieldValues 无法获取值

c# - 验证文件后错误无效的 json 原语

ios - 一指图像缩放/裁剪

asp.net - 设置 BasePage.vb 并创建 session 后,我的 URL 中有一个奇怪的查询字符串

asp.net - 使用适用于 dotnet core 的新 MSBuild 发布到 IIS?

c# - 不支持 EF6 嵌套事务

c# - 动态执行方法

ios - 如何在开关部分使用自定义类实例化 UITableViewCell